in reply to Help on Understanding Locks in Multithreading

Like that :)

http://search.cpan.org/~nwclark/perl-5.8.9/pod/perlthrtut.pod#Controlling_access:_lock()

  • Comment on Re: Help on Understanding Locks in Multithreading

Replies are listed 'Best First'.
Re^2: Help on Understanding Locks in Multithreading
by koti688 (Sexton) on Feb 25, 2009 at 11:12 UTC
    Thanks for the link.

    But i studied that already and i struck with this example.

    I am confused how the $foo variable is locked in the functions.

    Please explain the locking in this code , if you get anything. i am asking very basic things i guess :(

      What are you expecting, and what did you get which doesn't meet with your expectation ?

      FWIW, one wrinkle with threads is that the return context for the thread is set at threads->new time, not on the context of $thr->join(). Your code:

      $thr = threads->new(\&sub1, "THREAD1 :"); ... @ReturnData = $thr->join; ...
      should be:
      ($thr) = threads->new(\&sub1, "THREAD1 :"); ... @ReturnData = $thr->join; ...
      to provide the right context at the right time.

      The fragment:

      { lock $foo; $foo=0; }
      is reasonably plausible. You're locking $foo for just long enough to give it a new value -- so there is no possibility of some other thread attempting to read or change $foo while it's in any intermediate state -- provided they too lock $foo before doing anything with it. (The lock is dropped at the end of the block it is contained in.)

      I note that $foo is not initialised to anything.

      I note that you:

      print " Final value :$foo\n";
      without locking it. But that's probably OK, because $foo is only changed by the same thread.

      I wonder: you're not expecting $foo to work as some kind of semaphore, are you ?

      I am confused how the $foo variable is locked in the functions.
      Actually '$foo' itself isn't locked, execution access is locked. By that I mean that only one thread may be executing in the code blocks that have the 'lock' command at a time. And those blocks just happening to be modifying 'foo' (well, hopefully by design). The locks are controlling/limiting execution flow to a single thread at a time. This stops 2 threads from doing near simultaneous modifications to $foo.

      In the old days this code was called a 'critical code section'.

      It is always better to have seen your target for yourself, rather than depend upon someone else's description.
      Try using smaller numbers, not 1000/5000
      I am confused how the $foo variable is locked in the functions.
      Through the magic of perl threads? I'm sorry, I don't understand your question, but I don't think I could explain lock better than perlthrtut.

      Maybe it would be easier for you to understand if you told us where you got that code, what its supposed to do, etc?