Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Thread Synchronization Mechanism

by fluxion (Monk)
on May 23, 2004 at 04:40 UTC ( [id://355691]=note: print w/replies, xml ) Need Help??


in reply to Thread Synchronization Mechanism

I just recently started messing around with threads, so I haven't had alot of experience on the topic, but using semaphores seems like a possible solution. Here's an example:
#!/usr/bin/perl use strict; use threads; use Thread::Semaphore; my $semaphore = new Thread::Semaphore; $semaphore->down; sub code { my $job = $_[0]; $semaphore->down; print "$job\n"; } foreach (1..10) { threads->new(\&code, $_); } sleep 5; $semaphore->up(10);
Each thread stores it's argument, then attempts to decrement the resource count, since the initial $semaphore->down earlier in the script leaves the current resource count at 0, any new attempts at decrementing it cause the thread to block. When you want the threads to run, the resource count is set to 10, allowing the 10 blocked threads to unblock and execute. The code is untested.

Roses are red, violets are blue. All my base, are belong to you.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://355691]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (7)
As of 2024-04-18 08:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found