How to pass a hash link in multithreaded perl?

How do I pass the $ref hash link for the main thread and worker threads?

 #!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; my $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 { my ($ref) = @_; for ( my $i = 0; $i < 2; $i++ ) { $ref->{$i}->{handle} = new threads( \&issue_job, $ref, $i ); $ref->{$i}->{handle}->detach(); } } sub issue_job { my ( $ref, $i ) = @_; $ref->{$i}->{abc} = 555123 + $i; sleep(2); } 
+5
source share
1 answer

This does not work as good as you might think. One of the limitations of threads::shared is that it is great for exchanging one-dimensional containers, but when you try to work with nested data structures, it becomes rather messy, because the compiler does not know what it needs to exchange.

http://perldoc.perl.org/threads/shared.html#BUGS-AND-LIMITATIONS

So, for starters - you need to assign shared variables as shared. Or at the announcement:

 my $ref : shared; 

But since you are trying to use a hash

 shared_clone ( $ref ); 

But personally - I would shy away from such things. I do not like shared memory objects and usually prefer to use Thread::Semaphore and Thread::Queue and pass data back and forth in the queue. Storable helps with this, since you can freeze and thaw the data object to be inserted into the queue.

+5
source

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


All Articles