perlmonk1729 has asked for the wisdom of the Perl Monks concerning the following question:
I am having trouble updating a variable in a perl sub and using the updated value in the main body of the perl script. Ultimately, I'd like to share more complex data between the sub/callback and main. Any help would be greatly appreciated!
I am extending perl (with SWIG) to access a C library and also embedding a perl interepreter (via perl_clone) so that the library can invoke perl subroutines as callbacks.
The perl subs are getting called correctly. I need to wait in the main perl script until the callback is executed before other actions are taken. I initially initialized a simple scalar to "0" and changed its value in the subroutine and waited (sleep() ) until the value is updated. Though the callback updates the value, it is never reflected in the main body of the script. I'm not sure what is the reason?
As a possible solution, I declared the scalar as ":shared", but then I get this error on a unrelated line of code. The offending line is registering the perl-sub as a callback into the C library via a SWIG generated wrapper. Not sure of the link between "use threads:shared" and this message.
Perl version 5.8.8 threads version: 1.07, threads::shared version: 0.94
Original/ideal looking code sample..#This is the SWIG generated module to my C library use MyModule; #shared scalar $cb_done = 0; #This cb would be invoked by the cloned interpreter in the #C library. This works fine. sub cb_one { ($event, $pdata) = @_; #This line is printed. print "event : ", $event, "\n"; $cb_done = 1; } $status = MyModule::RegisterCB(\&main::cb_one); do { sleep (5); } until ($cb_done == 1) #This line is not printed as $cb_done never becomes 1 #in the main of the perl script print "CB was invoked : $cb_done\n";
Sample code using threads::shared
But I get "Invalid value for shared scalar" for this line of codeuse threads; use threads::shared; use MyModule; #shared scalar $cb_done : shared = 0;
$status = MyModule::RegisterCB(\&main::cb_one);
|
|---|