it didn't occur to me that the threads were actually sharing the FILE filehandle , so if one acquired the lock , each of them actually acquired the lock because FILE was shared amongst them( thanks tye for pointing that out )

I managed to pull of a quick replacement for that which works as one would expect.

Notice the 9-$x , that is to make sure that time(thread1)>time(thread2)>time(thread3)>... .

Also notice that $thread_lock are thread-specific locks

use strict; use warnings; use threads; use feature 'say' ; use Fcntl qw(:flock); my $file_path = ">>/tmp/test.txt"; open(FILE, $file_path); for(0..9) { threads->new(\&worker, $_); } $_->join for threads->list; sub worker { my $x = shift; my $locked; open(my $thread_lock,$file_path); $locked = flock($thread_lock, LOCK_EX|LOCK_NB ); if( $locked ) { say "$x: lock acquired"; sleep 9-$x; } else { say "$x: cannot acquire lock"; }; if($locked) { flock( $thread_lock, LOCK_UN ); print "$x: lock released\n"; } return; }
0: lock acquired 1: cannot acquire lock 2: cannot acquire lock 3: cannot acquire lock 4: cannot acquire lock 5: cannot acquire lock 6: cannot acquire lock 7: cannot acquire lock 8: cannot acquire lock 9: cannot acquire lock 0: lock released

In reply to Re^3: Slow worker threads by spx2
in thread Slow worker threads by pome23

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.