IO::Lambda::Thread - wait for blocking code using threads
The module implements a lambda wrapper that allows to asynchronously
wait for blocking code. The wrapping is done so that the code is
executed in another thread's context. IO::Lambda::Thread inherits
from IO::Lambda, and thus provides all function of the latter to
the caller. In particular, it is possible to wait for these objects
using tail, wait, any_tail etc standard waiter function.
use IO::Lambda qw(:lambda);
use IO::Lambda::Thread qw(threaded);
lambda {
context 0.1, threaded {
select(undef,undef,undef,0.8);
return "hello!";
};
any_tail {
if ( @_) {
print "done: ", $_[0]-> peek, "\n";
} else {
print "not yet\n";
again;
}
};
}-> wait;
Creates a new IO::Lambda::Thread object in the passive state. When the lambda
will be activated, a new thread will start, and $code code will be executed
in the context of this new thread. Upon successfull finish, result of $code
in list context will be stored on the lambda.
Sends KILL signal to the thread, executing the blocking code, and detaches it. Due to perl implementations of safe signals, the thread will not be killed immediately, but on the next possibility. Given that the module is specifically made for waiting on long, blocking calls, it is possible that such possibility can appear in rather long time.
threaded($code)Same as new but without a class.
Returns internal thread object
Joins the internal thread. Can be needed for perl versions before 5.10.0, that can't kill a thread reliably.
Threaded lambdas, just as normal lambdas, should be automatically destroyed
when their reference count goes down to zero. When they do so, they try to kill
whatever attached threads they have, using threads::detach and
threads::kill. However, this doesn't always work, may result in error
messages such as
Perl exited with active threads:
1 running and unjoined
0 finished and unjoined
0 running and detached
which means that some threads are still running. To avoid this problem,
kill leftover threaded lambdas with kill.
Note, that a reason that the reference counting does not goes to zero even when
a lambda goes out of scopy, may be because of the fact that lambda context,
which switches dynamically for each lambda callback, still contains the lambda.
$lambda-> clear empties the context, and thus any leftover references
from there.
the IO::Lambda manpage, the threads manpage.
Dmitry Karasik, <dmitry@karasik.eu.org>.