Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

threads::shared: lock a VARIABLE

by freakcoco (Sexton)
on Aug 22, 2016 at 14:30 UTC ( [id://1170172]=perlquestion: print w/replies, xml ) Need Help??

freakcoco has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I try to handle the multithread program.
I find that perl have a core module call threads, and it is seen to be solving the problem.
Then try to use threads, then the question arises.
I tried this use threads::shared's funciotn,
lock().
Complete code looks like:

#!/usr/bin/perl use utf8; use feature qw( say ); use threads; use threads::shared; use Data::Dumper; use Storable qw ( freeze thaw ); my $LockVar :shared; $LockVar = "default"; my $LockArray :shared; $Lock3Sec = threads->new( {'void' => 'void'}, sub { { say "the lock var default value is {$LockVar}"; lock($LockVar) or warn "cannot lock the var because {$!}\n +"; sleep 3; say $LockVar; } }, ); $Lock3Sec->detach(); $TryToReadLockVar = threads->new( {'void' => 'void'}, sub { my $count = 1; while( $LockVar eq 'default'){ say "try to modify the Lock var {$count} time"; $count += 1; $LockVar = 'this lock var has been change' or redo; } }, ); $TryToReadLockVar->join();

the out put is :

the lock var default value is {default} try to modify the Lock var {1} time
Feel it hasn't locked, and where it went wrong?

Replies are listed 'Best First'.
Re: threads::shared: lock a VARIABLE
by BrowserUk (Patriarch) on Aug 22, 2016 at 14:43 UTC
    where it went wrong?

    Nothing went wrong.

    1. Your first thread started, locked the variable, slept for 3 seconds, printed its value, got to the end of the block, where the lock was implicitly removed, and then the thread dies.
    2. Your second thread started, checked the value was 'default' -- which it must be -- incremented the count, modifed the variable, tested it for 'default' again -- which it couldn't possibly be -- and exits both the loop and thread.

    The only thing that might have stopped the second thread from modifying the variable, is if that second thread had attempted to acquire the lock. Which would have blocked until the first thread completed its sleep and exited its block thus releasing the lock.

    Either way, count will only ever be incremented once.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.

      So that's how it is, it will waiting for that.
      I changed the code like this:

      #!/usr/bin/perl use utf8; use feature qw( say ); use threads; use threads::shared; use Data::Dumper; use Storable qw ( freeze thaw ); my $Clock = threads-> new( {'context' => 'void'}, sub { my $count = 0; while(1){ say "programs implemented {$count} sec"; sleep 1; $count += 1; } } ); my $LockVar :shared; $LockVar = "default"; my $LockArray :shared; $LockArray = qw( You cannot lock the individual elements of a cont +ainer variable ); $Lock3Sec = threads->new( {'void' => 'void'}, sub { { say "the lock var default value is {$LockVar}"; lock($LockVar) or warn "cannot lock the var because {$ +!}\n"; sleep 3; say $LockVar; } }, ); $TryToReadLockVar = threads->new( {'void' => 'void'}, sub { my $count = 1; LINE: while( $LockVar eq 'default'){ say "try to modify the Lock var {$count} time"; $count += 1; $LockVar = 'this lock var has been change' or redo LIN +E; say "modify done"; } }, ); $TryToReadLockVar->join(); $Lock3Sec->detach(); $Clock->detach(); sleep 3;

      And the output is:

      programs implemented {0} sec the lock var default value is {default} try to modify the Lock var {1} time modify done programs implemented {1} sec programs implemented {2} sec programs implemented {3} sec this lock var has been change

      It doesn't seem like waiting properly
      The previous version of the program was all over in less than a second!
      Why it did not wait for the $Lock3Sec for three seconds, just unblock him $LockVar?
      Or It kill $Lock3Sec?

        Where in your code are you checking for whether the variable is locked or not? The locking is "advisory", that means you need to manually check for whether a variable is locked or not. See threads::shared. You need to call lock wherever you want to modify $LockVar:

        async { lock $LockVar; $LockVar = 'Haha'; sleep 3; print "Thread 1 +: $LockVar\n" }; async { lock $LockVar; $LockVar = 'Hehe'; sleep 3; print "Thread 2 +: $LockVar\n" };

        Personally, I try to stay away from approaches that require locks. Usually, a queue into which I can put new values and a single thread that reads from that queue and updates the master data at opportune times is sufficient. Or simply using a relational database as backend, as that takes care of the consistency for me. But if you're using threads, you most likely did so in the hope of gaining performance with short-lived calculations, which talking to a database usually precludes.

        Update: Here is how the locking could work in a self-contained example:

        #!perl -w use strict; use 5.010; use threads; use threads::shared; my $LockVar :shared; $LockVar = 'default'; async { lock $LockVar; my $oldLockVar= $LockVar; $LockVar = 'Haha'; sl +eep 3; say "Thread 1: set var from $oldLockVar to $LockVar" }; async { lock $LockVar; my $oldLockVar= $LockVar; $LockVar = 'Hehe'; sl +eep 5; say "Thread 2: set var from $oldLockVar to $LockVar" }; my $TryToReadLockVar = threads->new( {'void' => 'void'}, sub { my $count = 1; while( 1 ) { say "try to modify the Lock var {$count} time"; $count += 1; lock($LockVar); # !!! say "Now setting LockVar"; $LockVar = 'this lock var has been change'; last; } }, ); $TryToReadLockVar->join(); say "LockVar is now $LockVar"; __END__ try to modify the Lock var {1} time Thread 1: set var from default to Haha Thread 2: set var from Haha to Hehe Now setting LockVar LockVar is now this lock var has been change Perl exited with active threads: 0 running and unjoined 2 finished and unjoined 0 running and detached
Re: threads::shared: lock a VARIABLE
by hippo (Bishop) on Aug 22, 2016 at 14:44 UTC

    threads::shared locks are advisory (see the docs). You have to test for it in your TryToReadLockVar thread rather than just altering it regardless of the lock.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1170172]
Approved by QuillMeantTen
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-03-29 11:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found