OK, first off:
&__logger
Is probably not what you want to be doing. The ampersand denotes a function call, but does so in such a way as to avoid prototypes. I would imagine that's not what you want to do.\ (Functionally it's the same as:)
__logger(@_);
The reason your thing is erroring, is that it's running __logger() _before_ starting the threads. And using the return code from '__logger()' to figure out which thread to run:
use strict;
use warnings;
use Config;
use threads;
use threads::shared;
print("Config{useithreads} : " . $Config{"useithreads"} . "\n");
print("main starting\n");
my $t1 = threads->create(&__logger);
my $t2 = threads->create(&__logger);
$t1->join();
$t2->join();
sleep 12;
print("main done\n");
sub __logger
{
#threads->detach(); # raise the error "already detached"
print(threads -> self -> tid(). ":logger init\n");
sleep(10);
print(threads -> self -> tid(). ":logger closed\n");
return "fish";
}
Change the last line of logger to 'return "fish"' and you get the same error, with a different name, which illustrates perhaps a little more clearly what's going on - that return code _should_ be irrelevant, but threads -> create is evaluating the function call first. (And spawning an name like that is generally speaking a Bad Thing)
This is also of course, why your 'detach' isn't working - that sub isn't being run as a thread in the first place.
What you need to be doing is passing a 'code reference' into 'threads->create'. This should do what you expect:
use strict;
use warnings;
use Config;
use threads;
use threads::shared;
print("Config{useithreads} : " . $Config{"useithreads"} . "\n");
print("main starting\n");
my $t1 = threads->create(\&__logger);
my $t2 = threads->create(\&__logger);
$t1->join();
$t2->join();
print("main done\n");
sub __logger
{
#threads->detach(); # raise the error "already detached"
print(threads -> self -> tid(). ":logger init\n");
sleep(10);
print(threads -> self -> tid(). ":logger closed\n");
}
Putting the 'detach' back in works, but once you detach you can't join - and your program will create and then exit with threads still running. I'd suggest you don't usually want to do that, but if you really do, comment out the 'join' lines, and add a 'sleep 12' instead. |