What exactly does “locking” do in Perl?

I wrote a Perl script and noticed that my editor highlighted the word "lock". I was curious, so I looked at what the “castle” does in Perl, and could not find a direct answer (at least not one that I could fully understand).

This is the best answer I found: http://perldoc.perl.org/functions/lock.html


ex: lock THING

"puts an advisory lock on a shared variable or reference object contained in THING until the lock goes out of scope."


What exactly does this mean? The lock function is not used to lock files, because everything I read says that a "flock" is used for this, so why use a "lock"? Is it necessary to do this with threads and make sure that several processes running at the same time do not collide with each other?

+5
source share
2 answers

This is the main goal for multithreading. It locks the shared variable, so if any other thread tries to execute lock , then the lock call is blocked until it is released.

To illustrate:

 #!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; my $lock_var : shared; sub worker_thread { print threads -> self -> tid(). ": Waiting for lock\n"; lock ( $lock_var ); print threads -> self -> tid(). ": got lock, doing some pretend code\n"; sleep rand(10); #lock released when out of scope. } for ( 1..10 ) { threads -> create ( \&worker_thread ); } foreach my $thr ( threads -> list ) { $thr -> join(); } 

You can use it to manage resources to create a mutual exception, or you can use it to block, for example. hash when you want to update it without using another thread, doing it at the same time.

It should be noted that - lock not applicable. You can still change the shared variable, despite the lock . This is just a call to the lock function, which will check if the variable is currently unlocked.

When you perform variable manipulation, it is important to use lock . Any test in which you read->change->write can create a race condition, if you don’t block it, you cannot be sure that between reading and writing another thread will not do the same.

You can also see Thread::Semaphore , which does something similar.

+6
source

In terms of file locking, of which you seem to have some knowledge:

  • When you execute flock($fh, LOCK_EX) or die $!; , it locks until it gets a lock on this file. Two handles cannot hold the lock in this file at the same time.

  • When you do lock $var; , it will block until it gets the lock of this shared variable. None of the two threads can simultaneously block this shared variable.

As you can see, both provide a way to provide mutual access to some arbitrary resources.

Notes:

  • General variables exist inside the process, so lock $var; provides synchronization in the process. But it also means that you do not need to use any named external resources (such as a file).
+2
source

Source: https://habr.com/ru/post/1201430/


All Articles