freakcoco has asked for the wisdom of the Perl Monks concerning the following question:
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 :
Feel it hasn't locked, and where it went wrong?the lock var default value is {default} try to modify the Lock var {1} time
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: threads::shared: lock a VARIABLE
by BrowserUk (Patriarch) on Aug 22, 2016 at 14:43 UTC | |
by freakcoco (Sexton) on Aug 23, 2016 at 09:43 UTC | |
by Corion (Patriarch) on Aug 23, 2016 at 09:54 UTC | |
|
Re: threads::shared: lock a VARIABLE
by hippo (Archbishop) on Aug 22, 2016 at 14:44 UTC |