Coro

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

6.37 Tue Mar  4 13:27:33 CET 2014
	- *sigh*, removed leftover debugging code from debugging a
          perl bug, of all things.

6.36 Tue Mar  4 07:11:59 CET 2014
	- semaphores would not clear the destroy hook when interrupted
          by ->throw, causing segfaults or worse.
        - ->throw on a thread waiting for a semaphore did not acquire
          the semaphore, but also didn't wake up other waiters,
          possibly causing a deadlock.
	- "FATAL: $Coro::IDLE blocked itself" will now use Carp::confess
          to report a full stacktrace, which should help find out
          where the actual call is.
        - "atomically" destroy data in slf_destroy, because it is
          the right thing to do, just in case.
        - disable ecb.h libm dependency, to compile on ancient systems
          or under adverse conditions.

6.33 Mon Nov 18 11:26:27 CET 2013
	- do not crash when freeing padlists with holes (in 5.18).
	- tentative SVt_BIND 5.19 port/fix.

Changes  view on Meta::CPAN

        - removed timed_* functions - they were not being used anyways
          and should be replaced by a more generic mechanism -
          and were annoying to support anyways :)
        - removed SemaphoreSet's waiter method - use sem method instead.
        - Coro::Semaphore->adjust didn't correctly wake up enough waiters.
        - async_pool did free a scalar value twice
          ("Attempt to unreference...").
        - fix a longstanding bug where calling terminate on a coro that
          was waiting for a semaphore that was just becoming available
          would cause a deadlock (semaphore would get into a state where
          it was available but waiters were still blocked).
        - calling throw on a coroutine that is waiting for a semaphore will
          no longer make it acquire the semaphore (and thus leak a count).
        - perl's process emulation is now not even theoretically supported
          anymore.
        - new functions Coro::rouse_cb and Coro::rouse_wait for easier
          conversion of callback-style to blocking-style.
        - new methods $coro->schedule_to and ->cede_to, to specifically
          schedule or cede to a specific coroutine.
        - new function Coro::Semaphore::wait.
        - use named constants in Coro::Channel (Richard Hundt).

Changes  view on Meta::CPAN

          "Coro::State::transfer called while parsing" in many cases).

4.36 Sun Jan 13 10:53:56 CET 2008
	- reset diehook when terminating from an async_pool as to not
          trigger any __DIE__ handlers.

4.35 Sun Jan 13 04:14:13 CET 2008
	- "bt" debug command now displays any exceptions
          from longmess and also skips the innermost
          stackframes, giving more useufl output.
	- allow backtraces in coroutines blocked in Coro::EV,
          at a <1% speed hit.
        - handle localising of $SIG{__WARN__} and __DIE__
          properly (with a proper amount of dirty hacking).

4.34 Sat Dec 22 17:49:53 CET 2007
	- upgrade to EV version 2.0 API.

4.33 Mon Dec 17 08:36:12 CET 2007
	- make Coro::AIO etc. loadable in the absence of EV.

Coro.pm  view on Meta::CPAN

     cede; # yield back to main
     print "4\n";
  };
  print "1\n";
  cede; # yield to coro
  print "3\n";
  cede; # and again
  
  # use locking
  my $lock = new Coro::Semaphore;
  my $locked;
  
  $lock->down;
  $locked = 1;
  $lock->up;

=head1 DESCRIPTION

For a tutorial-style introduction, please read the L<Coro::Intro>
manpage. This manpage mainly contains reference information.

This module collection manages continuations in general, most often in
the form of cooperative threads (also called coros, or simply "coro"
in the documentation). They are similar to kernel threads but don't (in

Coro.pm  view on Meta::CPAN

=item terminate [arg...]

Terminates the current coro with the given status values (see
L<cancel>). The values will not be copied, but referenced directly.

=item Coro::on_enter BLOCK, Coro::on_leave BLOCK

These function install enter and leave winders in the current scope. The
enter block will be executed when on_enter is called and whenever the
current coro is re-entered by the scheduler, while the leave block is
executed whenever the current coro is blocked by the scheduler, and
also when the containing scope is exited (by whatever means, be it exit,
die, last etc.).

I<Neither invoking the scheduler, nor exceptions, are allowed within those
BLOCKs>. That means: do not even think about calling C<die> without an
eval, and do not even think of entering the scheduler in any way.

Since both BLOCKs are tied to the current scope, they will automatically
be removed when the current scope exits.

Coro.pm  view on Meta::CPAN

returning a new coderef. Unblocking means that calling the new coderef
will return immediately without blocking, returning nothing, while the
original code ref will be called (with parameters) from within another
coro.

The reason this function exists is that many event libraries (such as
the venerable L<Event|Event> module) are not thread-safe (a weaker form
of reentrancy). This means you must not block within event callbacks,
otherwise you might suffer from crashes or worse. The only event library
currently known that is safe to use without C<unblock_sub> is L<EV> (but
you might still run into deadlocks if all event loops are blocked).

Coro will try to catch you when you block in the event loop
("FATAL: $Coro::idle blocked itself"), but this is just best effort and
only works when you do not run your own event loop.

This function allows your callbacks to block by executing them in another
coro where it is safe to block. One example where blocking is handy
is when you use the L<Coro::AIO|Coro::AIO> functions to save results to
disk, for example.

In short: simply use C<unblock_sub { ... }> instead of C<sub { ... }> when
creating event callbacks that want to block.

Coro/AnyEvent.pm  view on Meta::CPAN

   }

You can also do nothing, in which case Coro::AnyEvent will invoke the event
loop as needed, which is less efficient, but sometimes very convenient.

What you I<MUST NOT EVER DO> is to block inside an event loop
callback. The reason is that most event loops are not reentrant and
this can cause a deadlock at best and corrupt memory at worst.

Coro will try to catch you when you block in the event loop
("FATAL: $Coro::IDLE blocked itself"), but this is just best effort and
only works when you do not run your own event loop.

To avoid this problem, start a new thread (e.g. with C<Coro::async_pool>)
or use C<Coro::unblock_sub> to run blocking tasks.

=head2 INVERSION OF CONTROL

If you need to wait for a single event, the rouse functions will come in
handy (see the Coro manpage for details):

Coro/Intro.pod  view on Meta::CPAN

ways. The first such primitives is L<Coro::Semaphore>, which implements
counting semaphores (binary semaphores are available as L<Coro::Signal>,
and there are L<Coro::SemaphoreSet> and L<Coro::RWLock> primitives as
well).

Counting semaphores, in a sense, store a count of resources. You can
remove/allocate/reserve a resource by calling the C<< ->down >> method,
which decrements the counter, and you can add or free a resource by
calling the C<< ->up >> method, which increments the counter. If the
counter is C<0>, then C<< ->down >> cannot decrement the semaphore - it is
locked - and the thread will wait until a count becomes available again.

Here is an example:

   use Coro;

   my $sem = new Coro::Semaphore 0; # a locked semaphore

   async {
      print "unlocking semaphore\n";
      $sem->up;
   };

   print "trying to lock semaphore\n";
   $sem->down;
   print "we got it!\n";

This program creates a I<locked> semaphore (a semaphore with count C<0>)
and tries to lock it (by trying to decrement it's counter in the C<down>
method). Since the semaphore count is already exhausted, this will block
the main thread until the semaphore becomes available.

This yields the CPU to the only other read thread in the process,t he
one created with C<async>, which unlocks the semaphore (and instantly
terminates itself by returning).

Since the semaphore is now available, the main program locks it and
continues: "we got it!".

Counting semaphores are most often used to lock resources, or to exclude
other threads from accessing or using a resource. For example, consider
a very costly function (that temporarily allocates a lot of ram, for
example). You wouldn't want to have many threads calling this function at
the same time, so you use a semaphore:

   my $lock = new Coro::Semaphore; # unlocked initially - default is 1

   sub costly_function {
      $lock->down; # acquire semaphore

      # do costly operation that blocks

      $lock->up; # unlock it
   }

No matter how many threads call C<costly_function>, only one will run

Coro/Intro.pod  view on Meta::CPAN

semaphore with an initial count of C<5>.

Why does the comment mention an "operation the blocks"? Again, that's
because coro's threads are cooperative: unless C<costly_function>
willingly gives up the CPU, other threads of control will simply not
run. This makes locking superfluous in cases where the function itself
never gives up the CPU, but when dealing with the outside world, this is
rare.

Now consider what happens when the code C<die>s after executing C<down>,
but before C<up>. This will leave the semaphore in a locked state, which
often isn't what you want - imagine the caller expecting a failure and
wrapping the call into an C<eval {}>.

So normally you would want to free the lock again if execution somehow
leaves the function, whether "normally" or via an exception. Here the
C<guard> method proves useful:

   my $lock = new Coro::Semaphore; # unlocked initially

   sub costly_function {
      my $guard = $lock->guard; # acquire guard

      # do costly operation that blocks
   }

The C<guard> method C<down>s the semaphore and returns a so-called guard
object. Nothing happens as long as there are references to it (i.e. it is
in scope somehow), but when all references are gone, for example, when

Coro/RWLock.pm  view on Meta::CPAN


 # or:
 $lck->wrlock; # acquire write lock
 $lck->tryrdlock; # try a readlock
 $lck->trywrlock; # try a write lock


=head1 DESCRIPTION

This module implements reader/write locks. A read can be acquired for
read by many coroutines in parallel as long as no writer has locked it
(shared access). A single write lock can be acquired when no readers
exist. RWLocks basically allow many concurrent readers (without writers)
OR a single writer (but no readers).

You don't have to load C<Coro::RWLock> manually, it will be loaded 
automatically when you C<use Coro> and call the C<new> constructor. 

=over 4

=cut

Coro/Semaphore.pm  view on Meta::CPAN


use common::sense;

use Coro ();

our $VERSION = 6.514;

=item new [initial count]

Creates a new sempahore object with the given initial lock count. The
default lock count is 1, which means it is unlocked by default. Zero (or
negative values) are also allowed, in which case the semaphore is locked
by default.

=item $sem->count

Returns the current semaphore count. The semaphore can be down'ed without
blocking when the count is strictly higher than C<0>.

=item $sem->adjust ($diff)

Atomically adds the amount given to the current semaphore count. If the

Coro/State.xs  view on Meta::CPAN

/** coroutine switching *****************************************************/

static void
transfer_check (pTHX_ struct coro *prev, struct coro *next)
{
  /* TODO: throwing up here is considered harmful */

  if (ecb_expect_true (prev != next))
    {
      if (ecb_expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
        croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,");

      if (ecb_expect_false (next->flags & (CF_RUNNING | CF_ZOMBIE | CF_SUSPENDED)))
        croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,");

#if !PERL_VERSION_ATLEAST (5,10,0)
      if (ecb_expect_false (PL_lex_state != LEX_NOTPARSING))
        croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,");
#endif
    }
}

Coro/State.xs  view on Meta::CPAN

                {
                  require_pv ("Carp");

                  {
                    dSP;

                    ENTER;
                    SAVETMPS;

                    PUSHMARK (SP);
                    XPUSHs (sv_2mortal (newSVpv ("FATAL: $Coro::idle blocked itself - did you try to block inside an event loop callback? Caught", 0)));
                    PUTBACK;
                    call_pv ("Carp::confess", G_VOID | G_DISCARD);

                    FREETMPS;
                    LEAVE;
                  }
                }

              ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */
              api_ready (aTHX_ SvRV (sv_idle));

Coro/libcoro/coro.c  view on Meta::CPAN

# endif

  coro_transfer (create_coro, new_coro);
}

/*****************************************************************************/
/* pthread backend                                                           */
/*****************************************************************************/
#elif CORO_PTHREAD

/* this mutex will be locked by the running coroutine */
pthread_mutex_t coro_mutex = PTHREAD_MUTEX_INITIALIZER;

struct coro_init_args
{
  coro_func func;
  void *arg;
  coro_context *self, *main;
};

static pthread_t null_tid;

README  view on Meta::CPAN

         cede; # yield back to main
         print "4\n";
      };
      print "1\n";
      cede; # yield to coro
      print "3\n";
      cede; # and again
  
      # use locking
      my $lock = new Coro::Semaphore;
      my $locked;
  
      $lock->down;
      $locked = 1;
      $lock->up;

DESCRIPTION
    For a tutorial-style introduction, please read the Coro::Intro manpage.
    This manpage mainly contains reference information.

    This module collection manages continuations in general, most often in
    the form of cooperative threads (also called coros, or simply "coro" in
    the documentation). They are similar to kernel threads but don't (in
    general) run in parallel at the same time even on SMP machines. The

README  view on Meta::CPAN

        ensure progress is made.

    terminate [arg...]
        Terminates the current coro with the given status values (see
        cancel). The values will not be copied, but referenced directly.

    Coro::on_enter BLOCK, Coro::on_leave BLOCK
        These function install enter and leave winders in the current scope.
        The enter block will be executed when on_enter is called and
        whenever the current coro is re-entered by the scheduler, while the
        leave block is executed whenever the current coro is blocked by the
        scheduler, and also when the containing scope is exited (by whatever
        means, be it exit, die, last etc.).

        *Neither invoking the scheduler, nor exceptions, are allowed within
        those BLOCKs*. That means: do not even think about calling "die"
        without an eval, and do not even think of entering the scheduler in
        any way.

        Since both BLOCKs are tied to the current scope, they will
        automatically be removed when the current scope exits.

README  view on Meta::CPAN

        coderef will return immediately without blocking, returning nothing,
        while the original code ref will be called (with parameters) from
        within another coro.

        The reason this function exists is that many event libraries (such
        as the venerable Event module) are not thread-safe (a weaker form of
        reentrancy). This means you must not block within event callbacks,
        otherwise you might suffer from crashes or worse. The only event
        library currently known that is safe to use without "unblock_sub" is
        EV (but you might still run into deadlocks if all event loops are
        blocked).

        Coro will try to catch you when you block in the event loop ("FATAL:
        $Coro::idle blocked itself"), but this is just best effort and only
        works when you do not run your own event loop.

        This function allows your callbacks to block by executing them in
        another coro where it is safe to block. One example where blocking
        is handy is when you use the Coro::AIO functions to save results to
        disk, for example.

        In short: simply use "unblock_sub { ... }" instead of "sub { ... }"
        when creating event callbacks that want to block.



( run in 0.606 second using v1.01-cache-2.11-cpan-26ccb49234f )