Async-Interrupt
view release on metacpan or search on metacpan
Interrupt.pm view on Meta::CPAN
=head1 SYNOPSIS
use Async::Interrupt;
=head1 DESCRIPTION
This module implements a single feature only of interest to advanced perl
modules, namely asynchronous interruptions (think "UNIX signals", which
are very similar).
Sometimes, modules wish to run code asynchronously (in another thread,
or from a signal handler), and then signal the perl interpreter on
certain events. One common way is to write some data to a pipe and use an
event handling toolkit to watch for I/O events. Another way is to send
a signal. Those methods are slow, and in the case of a pipe, also not
asynchronous - it won't interrupt a running perl interpreter.
This module implements asynchronous notifications that enable you to
signal running perl code from another thread, asynchronously, and
sometimes even without using a single syscall.
=head2 USAGE SCENARIOS
=over 4
=item Race-free signal handling
There seems to be no way to do race-free signal handling in perl: to
catch a signal, you have to execute Perl code, and between entering the
Interrupt.pm view on Meta::CPAN
will be queued, but perl signal handlers will not be executed and the
blocking syscall will not be interrupted.
You can use this module to bind a signal to a callback while at the same
time activating an event pipe that you can C<select> on, fixing the race
completely.
This can be used to implement the signal handling in event loops,
e.g. L<AnyEvent>, L<POE>, L<IO::Async::Loop> and so on.
=item Background threads want speedy reporting
Assume you want very exact timing, and you can spare an extra cpu core
for that. Then you can run an extra thread that signals your perl
interpreter. This means you can get a very exact timing source while your
perl code is number crunching, without even using a syscall to communicate
between your threads.
For example the deliantra game server uses a variant of this technique
to interrupt background processes regularly to send map updates to game
clients.
Or L<EV::Loop::Async> uses an interrupt object to wake up perl when new
events have arrived.
L<IO::AIO> and L<BDB> could also use this to speed up result reporting.
=item Speedy event loop invocation
One could use this module e.g. in L<Coro> to interrupt a running coro-thread
and cause it to enter the event loop.
Or one could bind to C<SIGIO> and tell some important sockets to send this
signal, causing the event loop to be entered to reduce network latency.
=back
=head2 HOW TO USE
You can use this module by creating an C<Async::Interrupt> object for each
Interrupt.pm view on Meta::CPAN
# two loops, just to be sure
while (%SIGNAL_RECEIVED) {
for (keys %SIGNAL_RECEIVED) {
delete $SIGNAL_RECEIVED{$_};
warn "signal $_ received\n";
}
}
}
=head2 Interrupt perl from another thread
This example interrupts the Perl interpreter from another thread, via the
XS API. This is used by e.g. the L<EV::Loop::Async> module.
On the Perl level, a new loop object (which contains the thread)
is created, by first calling some XS constructor, querying the
C-level callback function and feeding that as the C<c_cb> into the
Async::Interrupt constructor:
my $self = XS_thread_constructor;
my ($c_func, $c_arg) = _c_func $self; # return the c callback
my $asy = new Async::Interrupt c_cb => [$c_func, $c_arg];
Then the newly created Interrupt object is queried for the signaling
function that the newly created thread should call, and this is in turn
told to the thread object:
_attach $self, $asy->signal_func;
So to repeat: first the XS object is created, then it is queried for the
callback that should be called when the Interrupt object gets signalled.
Then the interrupt object is queried for the callback function that the
thread should call to signal the Interrupt object, and this callback is
then attached to the thread.
You have to be careful that your new thread is not signalling before the
signal function was configured, for example by starting the background
thread only within C<_attach>.
That concludes the Perl part.
The XS part consists of the actual constructor which creates a thread,
which is not relevant for this example, and two functions, C<_c_func>,
which returns the Perl-side callback, and C<_attach>, which configures
the signalling functioon that is safe toc all from another thread. For
simplicity, we will use global variables to store the functions, normally
you would somehow attach them to C<$self>.
The C<c_func> simply returns the address of a static function and arranges
for the object pointed to by C<$self> to be passed to it, as an integer:
void
_c_func (SV *loop)
PPCODE:
EXTEND (SP, 2);
Interrupt.pm view on Meta::CPAN
static void (*my_sig_func) (void *signal_arg, int value);
static void *my_sig_arg;
void
_attach (SV *loop_, IV sig_func, void *sig_arg)
CODE:
{
my_sig_func = sig_func;
my_sig_arg = sig_arg;
/* now run the thread */
thread_create (&u->tid, l_run, 0);
}
And C<l_run> (the background thread) would eventually call the signaling
function:
my_sig_func (my_sig_arg, 0);
You can have a look at L<EV::Loop::Async> for an actual example using
intra-thread communication, locking and so on.
=head1 THE Async::Interrupt CLASS
=over 4
=cut
package Async::Interrupt;
Interrupt.pm view on Meta::CPAN
Returns the address of a function to call asynchronously. The function
has the following prototype and needs to be passed the specified
C<$signal_arg>, which is a C<void *> cast to C<IV>:
void (*signal_func) (void *signal_arg, int value)
An example call would look like:
signal_func (signal_arg, 0);
The function is safe to call from within signal and thread contexts, at
any time. The specified C<value> is passed to both C and Perl callback.
C<$value> must be in the valid range for a C<sig_atomic_t>, except C<0>
(1..127 is portable).
If the function is called while the Async::Interrupt object is already
signaled but before the callbacks are being executed, then the stored
C<value> is either the old or the new one. Due to the asynchronous
nature of the code, the C<value> can even be passed to two consecutive
invocations of the callback.
Interrupt.pm view on Meta::CPAN
=item $async->unblock
Sometimes you need a "critical section" of code that will not be
interrupted by an Async::Interrupt. This can be implemented by calling C<<
$async->block >> before the critical section, and C<< $async->unblock >>
afterwards.
Note that there must be exactly one call of C<unblock> for every previous
call to C<block> (i.e. calls can nest).
Since ensuring this in the presence of exceptions and threads is
usually more difficult than you imagine, I recommend using C<<
$async->scoped_block >> instead.
=item $async->scope_block
This call C<< $async->block >> and installs a handler that is called when
the current scope is exited (via an exception, by canceling the Coro
thread, by calling last/goto etc.).
This is the recommended (and fastest) way to implement critical sections.
=item ($block_func, $block_arg) = $async->scope_block_func
Returns the address of a function that implements the C<scope_block>
functionality.
It has the following prototype and needs to be passed the specified
C<$block_arg>, which is a C<void *> cast to C<IV>:
Async::Interrupt - allow C/XS libraries to interrupt perl asynchronously
SYNOPSIS
use Async::Interrupt;
DESCRIPTION
This module implements a single feature only of interest to advanced
perl modules, namely asynchronous interruptions (think "UNIX signals",
which are very similar).
Sometimes, modules wish to run code asynchronously (in another thread,
or from a signal handler), and then signal the perl interpreter on
certain events. One common way is to write some data to a pipe and use
an event handling toolkit to watch for I/O events. Another way is to
send a signal. Those methods are slow, and in the case of a pipe, also
not asynchronous - it won't interrupt a running perl interpreter.
This module implements asynchronous notifications that enable you to
signal running perl code from another thread, asynchronously, and
sometimes even without using a single syscall.
USAGE SCENARIOS
Race-free signal handling
There seems to be no way to do race-free signal handling in perl: to
catch a signal, you have to execute Perl code, and between entering
the interpreter "select" function (or other blocking functions) and
executing the select syscall is a small but relevant timespan during
which signals will be queued, but perl signal handlers will not be
executed and the blocking syscall will not be interrupted.
You can use this module to bind a signal to a callback while at the
same time activating an event pipe that you can "select" on, fixing
the race completely.
This can be used to implement the signal handling in event loops,
e.g. AnyEvent, POE, IO::Async::Loop and so on.
Background threads want speedy reporting
Assume you want very exact timing, and you can spare an extra cpu
core for that. Then you can run an extra thread that signals your
perl interpreter. This means you can get a very exact timing source
while your perl code is number crunching, without even using a
syscall to communicate between your threads.
For example the deliantra game server uses a variant of this
technique to interrupt background processes regularly to send map
updates to game clients.
Or EV::Loop::Async uses an interrupt object to wake up perl when new
events have arrived.
IO::AIO and BDB could also use this to speed up result reporting.
Speedy event loop invocation
One could use this module e.g. in Coro to interrupt a running
coro-thread and cause it to enter the event loop.
Or one could bind to "SIGIO" and tell some important sockets to send
this signal, causing the event loop to be entered to reduce network
latency.
HOW TO USE
You can use this module by creating an "Async::Interrupt" object for
each such event source. This object stores a perl and/or a C-level
callback that is invoked when the "Async::Interrupt" object gets
signalled. It is executed at the next time the perl interpreter is
# two loops, just to be sure
while (%SIGNAL_RECEIVED) {
for (keys %SIGNAL_RECEIVED) {
delete $SIGNAL_RECEIVED{$_};
warn "signal $_ received\n";
}
}
}
Interrupt perl from another thread
This example interrupts the Perl interpreter from another thread, via
the XS API. This is used by e.g. the EV::Loop::Async module.
On the Perl level, a new loop object (which contains the thread) is
created, by first calling some XS constructor, querying the C-level
callback function and feeding that as the "c_cb" into the
Async::Interrupt constructor:
my $self = XS_thread_constructor;
my ($c_func, $c_arg) = _c_func $self; # return the c callback
my $asy = new Async::Interrupt c_cb => [$c_func, $c_arg];
Then the newly created Interrupt object is queried for the signaling
function that the newly created thread should call, and this is in turn
told to the thread object:
_attach $self, $asy->signal_func;
So to repeat: first the XS object is created, then it is queried for the
callback that should be called when the Interrupt object gets signalled.
Then the interrupt object is queried for the callback function that the
thread should call to signal the Interrupt object, and this callback is
then attached to the thread.
You have to be careful that your new thread is not signalling before the
signal function was configured, for example by starting the background
thread only within "_attach".
That concludes the Perl part.
The XS part consists of the actual constructor which creates a thread,
which is not relevant for this example, and two functions, "_c_func",
which returns the Perl-side callback, and "_attach", which configures
the signalling functioon that is safe toc all from another thread. For
simplicity, we will use global variables to store the functions,
normally you would somehow attach them to $self.
The "c_func" simply returns the address of a static function and
arranges for the object pointed to by $self to be passed to it, as an
integer:
void
_c_func (SV *loop)
PPCODE:
static void (*my_sig_func) (void *signal_arg, int value);
static void *my_sig_arg;
void
_attach (SV *loop_, IV sig_func, void *sig_arg)
CODE:
{
my_sig_func = sig_func;
my_sig_arg = sig_arg;
/* now run the thread */
thread_create (&u->tid, l_run, 0);
}
And "l_run" (the background thread) would eventually call the signaling
function:
my_sig_func (my_sig_arg, 0);
You can have a look at EV::Loop::Async for an actual example using
intra-thread communication, locking and so on.
THE Async::Interrupt CLASS
$async = new Async::Interrupt key => value...
Creates a new Async::Interrupt object. You may only use async
notifications on this object while it exists, so you need to keep a
reference to it at all times while it is used.
Optional constructor arguments include (normally you would specify
at least one of "cb" or "c_cb").
Returns the address of a function to call asynchronously. The
function has the following prototype and needs to be passed the
specified $signal_arg, which is a "void *" cast to "IV":
void (*signal_func) (void *signal_arg, int value)
An example call would look like:
signal_func (signal_arg, 0);
The function is safe to call from within signal and thread contexts,
at any time. The specified "value" is passed to both C and Perl
callback.
$value must be in the valid range for a "sig_atomic_t", except 0
(1..127 is portable).
If the function is called while the Async::Interrupt object is
already signaled but before the callbacks are being executed, then
the stored "value" is either the old or the new one. Due to the
asynchronous nature of the code, the "value" can even be passed to
$async->block
$async->unblock
Sometimes you need a "critical section" of code that will not be
interrupted by an Async::Interrupt. This can be implemented by
calling "$async->block" before the critical section, and
"$async->unblock" afterwards.
Note that there must be exactly one call of "unblock" for every
previous call to "block" (i.e. calls can nest).
Since ensuring this in the presence of exceptions and threads is
usually more difficult than you imagine, I recommend using
"$async->scoped_block" instead.
$async->scope_block
This call "$async->block" and installs a handler that is called when
the current scope is exited (via an exception, by canceling the Coro
thread, by calling last/goto etc.).
This is the recommended (and fastest) way to implement critical
sections.
($block_func, $block_arg) = $async->scope_block_func
Returns the address of a function that implements the "scope_block"
functionality.
It has the following prototype and needs to be passed the specified
$block_arg, which is a "void *" cast to "IV":
#define ECB_EXTERN_C_BEG ECB_EXTERN_C {
#define ECB_EXTERN_C_END }
#else
#define ECB_EXTERN_C extern
#define ECB_EXTERN_C_BEG
#define ECB_EXTERN_C_END
#endif
/*****************************************************************************/
/* ECB_NO_THREADS - ecb is not used by multiple threads, ever */
/* ECB_NO_SMP - ecb might be used in multiple threads, but only on a single cpu */
#if ECB_NO_THREADS
#define ECB_NO_SMP 1
#endif
#if ECB_NO_SMP
#define ECB_MEMORY_FENCE do { } while (0)
#endif
/* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/compiler_ref/compiler_builtins.html */
#define ECB_MEMORY_FENCE __asm__ __volatile__ ("tb1 0,%%r0,128" : : : "memory")
#elif defined __sh__
#define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
#endif
#endif
#endif
#ifndef ECB_MEMORY_FENCE
#if ECB_GCC_VERSION(4,7)
/* see comment below (stdatomic.h) about the C11 memory model. */
#define ECB_MEMORY_FENCE __atomic_thread_fence (__ATOMIC_SEQ_CST)
#define ECB_MEMORY_FENCE_ACQUIRE __atomic_thread_fence (__ATOMIC_ACQUIRE)
#define ECB_MEMORY_FENCE_RELEASE __atomic_thread_fence (__ATOMIC_RELEASE)
#define ECB_MEMORY_FENCE_RELAXED __atomic_thread_fence (__ATOMIC_RELAXED)
#elif ECB_CLANG_EXTENSION(c_atomic)
/* see comment below (stdatomic.h) about the C11 memory model. */
#define ECB_MEMORY_FENCE __c11_atomic_thread_fence (__ATOMIC_SEQ_CST)
#define ECB_MEMORY_FENCE_ACQUIRE __c11_atomic_thread_fence (__ATOMIC_ACQUIRE)
#define ECB_MEMORY_FENCE_RELEASE __c11_atomic_thread_fence (__ATOMIC_RELEASE)
#define ECB_MEMORY_FENCE_RELAXED __c11_atomic_thread_fence (__ATOMIC_RELAXED)
#elif ECB_GCC_VERSION(4,4) || defined __INTEL_COMPILER || defined __clang__
#define ECB_MEMORY_FENCE __sync_synchronize ()
#elif _MSC_VER >= 1500 /* VC++ 2008 */
/* apparently, microsoft broke all the memory barrier stuff in Visual Studio 2008... */
#pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
#define ECB_MEMORY_FENCE _ReadWriteBarrier (); MemoryBarrier()
#define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier (); MemoryBarrier() /* according to msdn, _ReadBarrier is not a load fence */
#define ECB_MEMORY_FENCE_RELEASE _WriteBarrier (); MemoryBarrier()
#elif _MSC_VER >= 1400 /* VC++ 2005 */
#elif __xlC__
#define ECB_MEMORY_FENCE __sync ()
#endif
#endif
#ifndef ECB_MEMORY_FENCE
#if ECB_C11 && !defined __STDC_NO_ATOMICS__
/* we assume that these memory fences work on all variables/all memory accesses, */
/* not just C11 atomics and atomic accesses */
#include <stdatomic.h>
#define ECB_MEMORY_FENCE atomic_thread_fence (memory_order_seq_cst)
#define ECB_MEMORY_FENCE_ACQUIRE atomic_thread_fence (memory_order_acquire)
#define ECB_MEMORY_FENCE_RELEASE atomic_thread_fence (memory_order_release)
#endif
#endif
#ifndef ECB_MEMORY_FENCE
#if !ECB_AVOID_PTHREADS
/*
* if you get undefined symbol references to pthread_mutex_lock,
* or failure to find pthread.h, then you should implement
* the ECB_MEMORY_FENCE operations for your cpu/compiler
* OR provide pthread.h and link against the posix thread library
* of your system.
*/
#include <pthread.h>
#define ECB_NEEDS_PTHREADS 1
#define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1
static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER;
#define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0)
#endif
#endif
#if !defined ECB_MEMORY_FENCE_ACQUIRE && defined ECB_MEMORY_FENCE
#define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
#endif
#if !defined ECB_MEMORY_FENCE_RELEASE && defined ECB_MEMORY_FENCE
#define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
#endif
if (epp->fd [1] != epp->fd [0])
close (epp->fd [1]);
epp->len = 0;
}
static void
s_epipe_signal (s_epipe *epp)
{
#ifdef _WIN32
/* perl overrides send with a function that crashes in other threads.
* unfortunately, it overrides it with an argument-less macro, so
* there is no way to force usage of the real send function.
* incompetent windows programmers - is this redundant?
*/
DWORD dummy;
WriteFile (S_TO_HANDLE (epp->fd [1]), (LPCVOID)&dummy, 1, &dummy, 0);
#else
static uint64_t counter = 1;
/* some modules accept fd's from outside, support eventfd here */
if (write (epp->fd [1], &counter, epp->len) < 0
( run in 0.513 second using v1.01-cache-2.11-cpan-3cd7ad12f66 )