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?

In reply to threads::shared: lock a VARIABLE by freakcoco

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.