in reply to Thread-safe modules and callbacks

Are you talking about a callback function that needs to keep track of some state, as in this example:
our $count = 0; sub my_callback { warn "I've been called ".(++$count)." times\n"; ... } my $thread = threads->create(..., \&my_callback); $thread->join; print "count = $count\n"; # prints 0
And the issue that this won't work in a threaded-environment because the $count that gets updated is only accessible in one thread (since it is not declared as shared.) So, callbacks have to be thread-aware if they are going to be used in a threaded environment.

Interesting problem...

Replies are listed 'Best First'.
Re^2: Thread-safe modules and callbacks
by Saladino (Beadle) on May 09, 2008 at 23:22 UTC
    Exactly that! Don't know if possible, it may be possible to access local variables of a function and that could let us delcare as shared dynamically callbacks variables. but that doesn't solve the problem when callback acess main threads variables.
      How about switching to objects, and create a closure for your callback:
      use threads::shared; my $obj = bless {}, 'foo'; sub foo::callback { warn "I've been called ".++($_[0]->{count})." times\n"; } share($obj); # only needed in a threaded environment my $thread = threads->create('start_thread', sub { $obj->callback(@_) +} ); $thread->join; print "count = ", $obj->{count}, "\n"; # prints 3 sub start_thread { my $cb = shift; for (1..3) { $cb->() } }
      Is there a way to implement function call behavior for a blessed reference? If so, you could have the best of both worlds.