multithreading - How to share hash reference in multithread perl? -
how share hash reference $ref
across main thread , worker threads ?
#!/usr/bin/perl utilize strict; utilize warnings; utilize threads; utilize threads::shared; $ref = {}; $ref->{0}->{abc} = 123; $ref->{1}->{abc} = 223; printf( "%d\n", $ref->{0}->{abc} ); printf( "%d\n", $ref->{1}->{abc} ); issue_all_jobs($ref); while (1) { printf( "%d\n", $ref->{0}->{abc} ); printf( "%d\n", $ref->{1}->{abc} ); sleep(1); } sub issue_all_jobs { ($ref) = @_; ( $i = 0; $i < 2; $i++ ) { $ref->{$i}->{handle} = new threads( \&issue_job, $ref, $i ); $ref->{$i}->{handle}->detach(); } } sub issue_job { ( $ref, $i ) = @_; $ref->{$i}->{abc} = 555123 + $i; sleep(2); }
this doesn't work might think. 1 of limitations of threads::shared
works fine sharing single dimensional containers, gets rather messy when trying work on nested info structures, because compiler doesn't 'know' needs share.
http://perldoc.perl.org/threads/shared.html#bugs-and-limitations
so - starters - need designate shared variables shared in first place. either @ declaration:
my $ref : shared;
but you're trying share hash
shared_clone ( $ref );
but - i'd shy away such things. dislike using shared memory objects, , prefer utilize thread::semaphore
, thread::queue
, pass info , forth in queue. storable
helps great deal this, can freeze
, thaw
info object insertion queue.
multithreading perl thread-safety
No comments:
Post a Comment