in reply to Re: Passing globs between threads
in thread Passing globs between threads
#!/usr/bin/perl -w use strict; use threads; use threads::shared; use IO::Handle; use Thread::Semaphore; # Here we've a choice - use Storable to freeze and thaw stuff, or # these two bogus implementations which do nothing. This illustrates # (when you use the bogus code) how you cannot simply drop blessed # objects into shared objects. If you use Storable, blessed objects # can be passed across while they're frozen, but file handles (for # example) still can't. use Storable qw{freeze thaw}; #sub freeze { ${$_[0]} } #sub thaw { \shift } # Job queue and semaphore; the semaphore gets signalled every time an # object is pushed onto the queue. my @queue : shared; my $queue_ctrl = Thread::Semaphore->new(0); sub thread { while(1) { $queue_ctrl->down; # Wait for something to be queued lock @queue; last unless @queue; # Terminate on empty packet my $object = ${ thaw shift @queue }; # Would normally receive something relatively complex and do some # work with it here. print "Thread received $object.\n"; } } # Note that I'm creating the thread *first* and *afterwards* passing # objects across (through the queue) for it to work with.. my $thr = threads->new(\&thread); # Things we want to try passing through to the thread: my @stuff = ( # A basic type, works no problem with or without freeze/thaw '"hi there"', # A blessed reference, must be frozen and thawed bless({}, 'Foo'), # We can pass STDIN's file descriptor as an integer STDIN->fileno, # Have to comment this next line out for successful completion - but # this (or some equivalent) is what I would like to achieve! *STDIN, ); # Queue stuff and see what happens foreach my $obj ( @stuff ) { { # Queue $obj and signal $queue_ctrl lock @queue; print "\nEnqueueing $obj...\n"; push @queue, freeze \$obj; $queue_ctrl->up; } sleep 1; # Optional, but gives the thread a chance to grab the queue } # Terminate - signal $queue_ctrl without enqueueing anything. $queue_ctrl->up; $thr->join;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Passing globs between threads
by BrowserUk (Patriarch) on Oct 01, 2004 at 00:21 UTC | |
by conrad (Beadle) on Oct 01, 2004 at 10:36 UTC | |
by BrowserUk (Patriarch) on Oct 02, 2004 at 06:17 UTC | |
by Anonymous Monk on Oct 01, 2004 at 20:09 UTC | |
by BrowserUk (Patriarch) on Oct 01, 2004 at 22:22 UTC | |
by Anonymous Monk on Oct 02, 2004 at 00:27 UTC | |
by BrowserUk (Patriarch) on Oct 02, 2004 at 04:56 UTC | |
|