-- Back to Index --
In this post, we are talking about Thread Synchronization
.
First in Perl
:
#!/usr/bin/env perl
use v5.38;
use threads;
use threads::shared;
use Thread::Semaphore;
my $semaphore = Thread::Semaphore->new(1);
my $resource :shared = 0;
sub worker {
my $id = shift;
$semaphore->down();
$resource++;
say "In thread $id, shared resource=$resource";
$semaphore->up();
}
threads->create(\&worker, $_)->join foreach 1..5;
say "Final value of shared resource=$resource";
Time to test the code:
$ perl thread-sync.pl
In thread 1, shared resource=1
In thread 2, shared resource=2
In thread 3, shared resource=3
In thread 4, shared resource=4
In thread 5, shared resource=5
Final value of shared resource=5
I got this suggestion (below) on social platform by Füsilier Breitlinger
:
#!/usr/bin/env perl
use v5.38;
use threads;
use threads::shared;
my $resource :shared = 0;
sub worker {
my $id = shift;
lock $resource;
$resource++;
say "In thread $id, shared resource=$resource";
}
threads->create(\&worker, $_)->join foreach 1..5;
say "Final value of shared resource=$resource";
I liked this, as it does the same job with less code.
Let's do the same in Python
:
#!/usr/bin/env python3
import threading
lock = threading.Lock()
resource = 0
def worker(id):
global resource
with lock:
resource += 1
print(f"In thread {id}, shared {resource=}")
threads = []
for i in range(1, 6):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"Final value of shared {resource=}")
Run the code now:
$ python3 thread-sync.py
In thread 1, shared resource=1
In thread 2, shared resource=2
In thread 4, shared resource=3
In thread 3, shared resource=4
In thread 5, shared resource=5
Final value of shared resource=5
-- Back to Index --