I believe the problem here is the multiple calls to tie() within the same file. I, too, have been struggling to use IPC::Shareable with fork(), but I thought I'd revisit it since it came up here.
This code, refactored from a very old version of the Perl Cookbook, does what you want (I believe). Notice that there's only one call to tie(). The only places I can find that there are multiple calls is when each process is created within a different file. I'm not entirely certain yet.
Also note that I tested this with hashes, arrays and scalars along with the hash reference I've left in, and it also works with subroutines, which I left out. One last thing... the 'glue' appears to require undef when using it in this way. When I try a named glue, it fails (without the 'create' param set to true, which technically isn't needed unless an external process is using the var... again, at least from what I can tell.
use warnings; use strict; use IPC::Shareable; $SIG{INT} = sub { exit; }; my $href = {count => 0}; my $ipc = tie $href, 'IPC::Shareable', undef, { destroy => 1 }; for (1 .. 3) { unless (fork()){ while (1){ $ipc->shlock(); $href->{count}++; $href->{pid} = $$; $ipc->shunlock(); } exit; } } while (1) { next if ! defined $href->{pid}; print "pid: $href->{pid}, count: $href->{count}\n"; sleep 1; }
Output:
pid: 19062, count: 1 pid: 19062, count: 1472 pid: 19063, count: 3070 pid: 19063, count: 4771 pid: 19062, count: 6548 pid: 19062, count: 8179 pid: 19062, count: 10070 pid: 19064, count: 11817 ^C
In reply to Re: IPC:Shareable: Sharing an object between parallel processes
by stevieb
in thread IPC:Shareable: Sharing an object between parallel processes
by Bloehdian
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |