Coro-6.55/0000755000000000000000000000000013514362055011055 5ustar rootrootCoro-6.55/README0000644000000000000000000013455713514362055011754 0ustar rootrootNAME Coro - the only real threads in perl SYNOPSIS use Coro; async { # some asynchronous thread of execution print "2\n"; 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 specific flavor of thread offered by this module also guarantees you that it will not switch between threads unless necessary, at easily-identified points in your program, so locking and parallel access are rarely an issue, making thread programming much safer and easier than using other thread models. Unlike the so-called "Perl threads" (which are not actually real threads but only the windows process emulation (see section of same name for more details) ported to UNIX, and as such act as processes), Coro provides a full shared address space, which makes communication between threads very easy. And coro threads are fast, too: disabling the Windows process emulation code in your perl and using Coro can easily result in a two to four times speed increase for your programs. A parallel matrix multiplication benchmark (very communication-intensive) runs over 300 times faster on a single core than perls pseudo-threads on a quad core using all four cores. Coro achieves that by supporting multiple running interpreters that share data, which is especially useful to code pseudo-parallel processes and for event-based programming, such as multiple HTTP-GET requests running concurrently. See Coro::AnyEvent to learn more on how to integrate Coro into an event-based environment. In this module, a thread is defined as "callchain + lexical variables + some package variables + C stack), that is, a thread has its own callchain, its own set of lexicals and its own set of perls most important global variables (see Coro::State for more configuration and background info). See also the "SEE ALSO" section at the end of this document - the Coro module family is quite large. CORO THREAD LIFE CYCLE During the long and exciting (or not) life of a coro thread, it goes through a number of states: 1. Creation The first thing in the life of a coro thread is its creation - obviously. The typical way to create a thread is to call the "async BLOCK" function: async { # thread code goes here }; You can also pass arguments, which are put in @_: async { print $_[1]; # prints 2 } 1, 2, 3; This creates a new coro thread and puts it into the ready queue, meaning it will run as soon as the CPU is free for it. "async" will return a Coro object - you can store this for future reference or ignore it - a thread that is running, ready to run or waiting for some event is alive on its own. Another way to create a thread is to call the "new" constructor with a code-reference: new Coro sub { # thread code goes here }, @optional_arguments; This is quite similar to calling "async", but the important difference is that the new thread is not put into the ready queue, so the thread will not run until somebody puts it there. "async" is, therefore, identical to this sequence: my $coro = new Coro sub { # thread code goes here }; $coro->ready; return $coro; 2. Startup When a new coro thread is created, only a copy of the code reference and the arguments are stored, no extra memory for stacks and so on is allocated, keeping the coro thread in a low-memory state. Only when it actually starts executing will all the resources be finally allocated. The optional arguments specified at coro creation are available in @_, similar to function calls. 3. Running / Blocking A lot can happen after the coro thread has started running. Quite usually, it will not run to the end in one go (because you could use a function instead), but it will give up the CPU regularly because it waits for external events. As long as a coro thread runs, its Coro object is available in the global variable $Coro::current. The low-level way to give up the CPU is to call the scheduler, which selects a new coro thread to run: Coro::schedule; Since running threads are not in the ready queue, calling the scheduler without doing anything else will block the coro thread forever - you need to arrange either for the coro to put woken up (readied) by some other event or some other thread, or you can put it into the ready queue before scheduling: # this is exactly what Coro::cede does $Coro::current->ready; Coro::schedule; All the higher-level synchronisation methods (Coro::Semaphore, Coro::rouse_*...) are actually implemented via "->ready" and "Coro::schedule". While the coro thread is running it also might get assigned a C-level thread, or the C-level thread might be unassigned from it, as the Coro runtime wishes. A C-level thread needs to be assigned when your perl thread calls into some C-level function and that function in turn calls perl and perl then wants to switch coroutines. This happens most often when you run an event loop and block in the callback, or when perl itself calls some function such as "AUTOLOAD" or methods via the "tie" mechanism. 4. Termination Many threads actually terminate after some time. There are a number of ways to terminate a coro thread, the simplest is returning from the top-level code reference: async { # after returning from here, the coro thread is terminated }; async { return if 0.5 < rand; # terminate a little earlier, maybe print "got a chance to print this\n"; # or here }; Any values returned from the coroutine can be recovered using "->join": my $coro = async { "hello, world\n" # return a string }; my $hello_world = $coro->join; print $hello_world; Another way to terminate is to call "Coro::terminate", which at any subroutine call nesting level: async { Coro::terminate "return value 1", "return value 2"; }; Yet another way is to "->cancel" (or "->safe_cancel") the coro thread from another thread: my $coro = async { exit 1; }; $coro->cancel; # also accepts values for ->join to retrieve Cancellation *can* be dangerous - it's a bit like calling "exit" without actually exiting, and might leave C libraries and XS modules in a weird state. Unlike other thread implementations, however, Coro is exceptionally safe with regards to cancellation, as perl will always be in a consistent state, and for those cases where you want to do truly marvellous things with your coro while it is being cancelled - that is, make sure all cleanup code is executed from the thread being cancelled - there is even a "->safe_cancel" method. So, cancelling a thread that runs in an XS event loop might not be the best idea, but any other combination that deals with perl only (cancelling when a thread is in a "tie" method or an "AUTOLOAD" for example) is safe. Last not least, a coro thread object that isn't referenced is "->cancel"'ed automatically - just like other objects in Perl. This is not such a common case, however - a running thread is referencedy by $Coro::current, a thread ready to run is referenced by the ready queue, a thread waiting on a lock or semaphore is referenced by being in some wait list and so on. But a thread that isn't in any of those queues gets cancelled: async { schedule; # cede to other coros, don't go into the ready queue }; cede; # now the async above is destroyed, as it is not referenced by anything. A slightly embellished example might make it clearer: async { my $guard = Guard::guard { print "destroyed\n" }; schedule while 1; }; cede; Superficially one might not expect any output - since the "async" implements an endless loop, the $guard will not be cleaned up. However, since the thread object returned by "async" is not stored anywhere, the thread is initially referenced because it is in the ready queue, when it runs it is referenced by $Coro::current, but when it calls "schedule", it gets "cancel"ed causing the guard object to be destroyed (see the next section), and printing its message. If this seems a bit drastic, remember that this only happens when nothing references the thread anymore, which means there is no way to further execute it, ever. The only options at this point are leaking the thread, or cleaning it up, which brings us to... 5. Cleanup Threads will allocate various resources. Most but not all will be returned when a thread terminates, during clean-up. Cleanup is quite similar to throwing an uncaught exception: perl will work its way up through all subroutine calls and blocks. On its way, it will release all "my" variables, undo all "local"'s and free any other resources truly local to the thread. So, a common way to free resources is to keep them referenced only by my variables: async { my $big_cache = new Cache ...; }; If there are no other references, then the $big_cache object will be freed when the thread terminates, regardless of how it does so. What it does "NOT" do is unlock any Coro::Semaphores or similar resources, but that's where the "guard" methods come in handy: my $sem = new Coro::Semaphore; async { my $lock_guard = $sem->guard; # if we return, or die or get cancelled, here, # then the semaphore will be "up"ed. }; The "Guard::guard" function comes in handy for any custom cleanup you might want to do (but you cannot switch to other coroutines from those code blocks): async { my $window = new Gtk2::Window "toplevel"; # The window will not be cleaned up automatically, even when $window # gets freed, so use a guard to ensure its destruction # in case of an error: my $window_guard = Guard::guard { $window->destroy }; # we are safe here }; Last not least, "local" can often be handy, too, e.g. when temporarily replacing the coro thread description: sub myfunction { local $Coro::current->{desc} = "inside myfunction(@_)"; # if we return or die here, the description will be restored } 6. Viva La Zombie Muerte Even after a thread has terminated and cleaned up its resources, the Coro object still is there and stores the return values of the thread. When there are no other references, it will simply be cleaned up and freed. If there areany references, the Coro object will stay around, and you can call "->join" as many times as you wish to retrieve the result values: async { print "hi\n"; 1 }; # run the async above, and free everything before returning # from Coro::cede: Coro::cede; { my $coro = async { print "hi\n"; 1 }; # run the async above, and clean up, but do not free the coro # object: Coro::cede; # optionally retrieve the result values my @results = $coro->join; # now $coro goes out of scope, and presumably gets freed }; GLOBAL VARIABLES $Coro::main This variable stores the Coro object that represents the main program. While you can "ready" it and do most other things you can do to coro, it is mainly useful to compare again $Coro::current, to see whether you are running in the main program or not. $Coro::current The Coro object representing the current coro (the last coro that the Coro scheduler switched to). The initial value is $Coro::main (of course). This variable is strictly *read-only*. You can take copies of the value stored in it and use it as any other Coro object, but you must not otherwise modify the variable itself. $Coro::idle This variable is mainly useful to integrate Coro into event loops. It is usually better to rely on Coro::AnyEvent or Coro::EV, as this is pretty low-level functionality. This variable stores a Coro object that is put into the ready queue when there are no other ready threads (without invoking any ready hooks). The default implementation dies with "FATAL: deadlock detected.", followed by a thread listing, because the program has no other way to continue. This hook is overwritten by modules such as "Coro::EV" and "Coro::AnyEvent" to wait on an external event that hopefully wakes up a coro so the scheduler can run it. See Coro::EV or Coro::AnyEvent for examples of using this technique. SIMPLE CORO CREATION async { ... } [@args...] Create a new coro and return its Coro object (usually unused). The coro will be put into the ready queue, so it will start running automatically on the next scheduler run. The first argument is a codeblock/closure that should be executed in the coro. When it returns argument returns the coro is automatically terminated. The remaining arguments are passed as arguments to the closure. See the "Coro::State::new" constructor for info about the coro environment in which coro are executed. Calling "exit" in a coro will do the same as calling exit outside the coro. Likewise, when the coro dies, the program will exit, just as it would in the main program. If you do not want that, you can provide a default "die" handler, or simply avoid dieing (by use of "eval"). Example: Create a new coro that just prints its arguments. async { print "@_\n"; } 1,2,3,4; async_pool { ... } [@args...] Similar to "async", but uses a coro pool, so you should not call terminate or join on it (although you are allowed to), and you get a coro that might have executed other code already (which can be good or bad :). On the plus side, this function is about twice as fast as creating (and destroying) a completely new coro, so if you need a lot of generic coros in quick successsion, use "async_pool", not "async". The code block is executed in an "eval" context and a warning will be issued in case of an exception instead of terminating the program, as "async" does. As the coro is being reused, stuff like "on_destroy" will not work in the expected way, unless you call terminate or cancel, which somehow defeats the purpose of pooling (but is fine in the exceptional case). The priority will be reset to 0 after each run, all "swap_sv" calls will be undone, tracing will be disabled, the description will be reset and the default output filehandle gets restored, so you can change all these. Otherwise the coro will be re-used "as-is": most notably if you change other per-coro global stuff such as $/ you *must needs* revert that change, which is most simply done by using local as in: "local $/". The idle pool size is limited to 8 idle coros (this can be adjusted by changing $Coro::POOL_SIZE), but there can be as many non-idle coros as required. If you are concerned about pooled coros growing a lot because a single "async_pool" used a lot of stackspace you can e.g. "async_pool { terminate }" once per second or so to slowly replenish the pool. In addition to that, when the stacks used by a handler grows larger than 32kb (adjustable via $Coro::POOL_RSS) it will also be destroyed. STATIC METHODS Static methods are actually functions that implicitly operate on the current coro. schedule Calls the scheduler. The scheduler will find the next coro that is to be run from the ready queue and switches to it. The next coro to be run is simply the one with the highest priority that is longest in its ready queue. If there is no coro ready, it will call the $Coro::idle hook. Please note that the current coro will *not* be put into the ready queue, so calling this function usually means you will never be called again unless something else (e.g. an event handler) calls "->ready", thus waking you up. This makes "schedule" *the* generic method to use to block the current coro and wait for events: first you remember the current coro in a variable, then arrange for some callback of yours to call "->ready" on that once some event happens, and last you call "schedule" to put yourself to sleep. Note that a lot of things can wake your coro up, so you need to check whether the event indeed happened, e.g. by storing the status in a variable. See HOW TO WAIT FOR A CALLBACK, below, for some ways to wait for callbacks. cede "Cede" to other coros. This function puts the current coro into the ready queue and calls "schedule", which has the effect of giving up the current "timeslice" to other coros of the same or higher priority. Once your coro gets its turn again it will automatically be resumed. This function is often called "yield" in other languages. Coro::cede_notself Works like cede, but is not exported by default and will cede to *any* coro, regardless of priority. This is useful sometimes to 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. These functions implement the same concept as "dynamic-wind" in scheme does, and are useful when you want to localise some resource to a specific coro. They slow down thread switching considerably for coros that use them (about 40% for a BLOCK with a single assignment, so thread switching is still reasonably fast if the handlers are fast). These functions are best understood by an example: The following function will change the current timezone to "Antarctica/South_Pole", which requires a call to "tzset", but by using "on_enter" and "on_leave", which remember/change the current timezone and restore the previous value, respectively, the timezone is only changed for the coro that installed those handlers. use POSIX qw(tzset); async { my $old_tz; # store outside TZ value here Coro::on_enter { $old_tz = $ENV{TZ}; # remember the old value $ENV{TZ} = "Antarctica/South_Pole"; tzset; # enable new value }; Coro::on_leave { $ENV{TZ} = $old_tz; tzset; # restore old value }; # at this place, the timezone is Antarctica/South_Pole, # without disturbing the TZ of any other coro. }; This can be used to localise about any resource (locale, uid, current working directory etc.) to a block, despite the existence of other coros. Another interesting example implements time-sliced multitasking using interval timers (this could obviously be optimised, but does the job): # "timeslice" the given block sub timeslice(&) { use Time::HiRes (); Coro::on_enter { # on entering the thread, we set an VTALRM handler to cede $SIG{VTALRM} = sub { cede }; # and then start the interval timer Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01; }; Coro::on_leave { # on leaving the thread, we stop the interval timer again Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0; }; &{+shift}; } # use like this: timeslice { # The following is an endless loop that would normally # monopolise the process. Since it runs in a timesliced # environment, it will regularly cede to other threads. while () { } }; killall Kills/terminates/cancels all coros except the currently running one. Note that while this will try to free some of the main interpreter resources if the calling coro isn't the main coro, but one cannot free all of them, so if a coro that is not the main coro calls this function, there will be some one-time resource leak. CORO OBJECT METHODS These are the methods you can call on coro objects (or to create them). new Coro \&sub [, @args...] Create a new coro and return it. When the sub returns, the coro automatically terminates as if "terminate" with the returned values were called. To make the coro run you must first put it into the ready queue by calling the ready method. See "async" and "Coro::State::new" for additional info about the coro environment. $success = $coro->ready Put the given coro into the end of its ready queue (there is one queue for each priority) and return true. If the coro is already in the ready queue, do nothing and return false. This ensures that the scheduler will resume this coro automatically once all the coro of higher priority and all coro of the same priority that were put into the ready queue earlier have been resumed. $coro->suspend Suspends the specified coro. A suspended coro works just like any other coro, except that the scheduler will not select a suspended coro for execution. Suspending a coro can be useful when you want to keep the coro from running, but you don't want to destroy it, or when you want to temporarily freeze a coro (e.g. for debugging) to resume it later. A scenario for the former would be to suspend all (other) coros after a fork and keep them alive, so their destructors aren't called, but new coros can be created. $coro->resume If the specified coro was suspended, it will be resumed. Note that when the coro was in the ready queue when it was suspended, it might have been unreadied by the scheduler, so an activation might have been lost. To avoid this, it is best to put a suspended coro into the ready queue unconditionally, as every synchronisation mechanism must protect itself against spurious wakeups, and the one in the Coro family certainly do that. $state->is_new Returns true iff this Coro object is "new", i.e. has never been run yet. Those states basically consist of only the code reference to call and the arguments, but consumes very little other resources. New states will automatically get assigned a perl interpreter when they are transferred to. $state->is_zombie Returns true iff the Coro object has been cancelled, i.e. its resources freed because they were "cancel"'ed, "terminate"'d, "safe_cancel"'ed or simply went out of scope. The name "zombie" stems from UNIX culture, where a process that has exited and only stores and exit status and no other resources is called a "zombie". $is_ready = $coro->is_ready Returns true iff the Coro object is in the ready queue. Unless the Coro object gets destroyed, it will eventually be scheduled by the scheduler. $is_running = $coro->is_running Returns true iff the Coro object is currently running. Only one Coro object can ever be in the running state (but it currently is possible to have multiple running Coro::States). $is_suspended = $coro->is_suspended Returns true iff this Coro object has been suspended. Suspended Coros will not ever be scheduled. $coro->cancel ($arg...) Terminate the given Coro thread and make it return the given arguments as status (default: an empty list). Never returns if the Coro is the current Coro. This is a rather brutal way to free a coro, with some limitations - if the thread is inside a C callback that doesn't expect to be canceled, bad things can happen, or if the cancelled thread insists on running complicated cleanup handlers that rely on its thread context, things will not work. Any cleanup code being run (e.g. from "guard" blocks, destructors and so on) will be run without a thread context, and is not allowed to switch to other threads. A common mistake is to call "->cancel" from a destructor called by die'ing inside the thread to be cancelled for example. On the plus side, "->cancel" will always clean up the thread, no matter what. If your cleanup code is complex or you want to avoid cancelling a C-thread that doesn't know how to clean up itself, it can be better to "->throw" an exception, or use "->safe_cancel". The arguments to "->cancel" are not copied, but instead will be referenced directly (e.g. if you pass $var and after the call change that variable, then you might change the return values passed to e.g. "join", so don't do that). The resources of the Coro are usually freed (or destructed) before this call returns, but this can be delayed for an indefinite amount of time, as in some cases the manager thread has to run first to actually destruct the Coro object. $coro->safe_cancel ($arg...) Works mostly like "->cancel", but is inherently "safer", and consequently, can fail with an exception in cases the thread is not in a cancellable state. Essentially, "->safe_cancel" is a "->cancel" with extra checks before canceling. It works a bit like throwing an exception that cannot be caught - specifically, it will clean up the thread from within itself, so all cleanup handlers (e.g. "guard" blocks) are run with full thread context and can block if they wish. The downside is that there is no guarantee that the thread can be cancelled when you call this method, and therefore, it might fail. It is also considerably slower than "cancel" or "terminate". A thread is in a safe-cancellable state if it either has never been run yet, has already been canceled/terminated or otherwise destroyed, or has no C context attached and is inside an SLF function. The first two states are trivial - a thread that hasnot started or has already finished is safe to cancel. The last state basically means that the thread isn't currently inside a perl callback called from some C function (usually via some XS modules) and isn't currently executing inside some C function itself (via Coro's XS API). This call returns true when it could cancel the thread, or croaks with an error otherwise (i.e. it either returns true or doesn't return at all). Why the weird interface? Well, there are two common models on how and when to cancel things. In the first, you have the expectation that your coro thread can be cancelled when you want to cancel it - if the thread isn't cancellable, this would be a bug somewhere, so "->safe_cancel" croaks to notify of the bug. In the second model you sometimes want to ask nicely to cancel a thread, but if it's not a good time, well, then don't cancel. This can be done relatively easy like this: if (! eval { $coro->safe_cancel }) { warn "unable to cancel thread: $@"; } However, what you never should do is first try to cancel "safely" and if that fails, cancel the "hard" way with "->cancel". That makes no sense: either you rely on being able to execute cleanup code in your thread context, or you don't. If you do, then "->safe_cancel" is the only way, and if you don't, then "->cancel" is always faster and more direct. $coro->schedule_to Puts the current coro to sleep (like "Coro::schedule"), but instead of continuing with the next coro from the ready queue, always switch to the given coro object (regardless of priority etc.). The readyness state of that coro isn't changed. This is an advanced method for special cases - I'd love to hear about any uses for this one. $coro->cede_to Like "schedule_to", but puts the current coro into the ready queue. This has the effect of temporarily switching to the given coro, and continuing some time later. This is an advanced method for special cases - I'd love to hear about any uses for this one. $coro->throw ([$scalar]) If $throw is specified and defined, it will be thrown as an exception inside the coro at the next convenient point in time. Otherwise clears the exception object. Coro will check for the exception each time a schedule-like-function returns, i.e. after each "schedule", "cede", "Coro::Semaphore->down", "Coro::Handle->readable" and so on. Most of those functions (all that are part of Coro itself) detect this case and return early in case an exception is pending. The exception object will be thrown "as is" with the specified scalar in $@, i.e. if it is a string, no line number or newline will be appended (unlike with "die"). This can be used as a softer means than either "cancel" or "safe_cancel "to ask a coro to end itself, although there is no guarantee that the exception will lead to termination, and if the exception isn't caught it might well end the whole program. You might also think of "throw" as being the moral equivalent of "kill"ing a coro with a signal (in this case, a scalar). $coro->join Wait until the coro terminates and return any values given to the "terminate" or "cancel" functions. "join" can be called concurrently from multiple threads, and all will be resumed and given the status return once the $coro terminates. $coro->on_destroy (\&cb) Registers a callback that is called when this coro thread gets destroyed, that is, after its resources have been freed but before it is joined. The callback gets passed the terminate/cancel arguments, if any, and *must not* die, under any circumstances. There can be any number of "on_destroy" callbacks per coro, and there is currently no way to remove a callback once added. $oldprio = $coro->prio ($newprio) Sets (or gets, if the argument is missing) the priority of the coro thread. Higher priority coro get run before lower priority coros. Priorities are small signed integers (currently -4 .. +3), that you can refer to using PRIO_xxx constants (use the import tag :prio to get then): PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN 3 > 1 > 0 > -1 > -3 > -4 # set priority to HIGH current->prio (PRIO_HIGH); The idle coro thread ($Coro::idle) always has a lower priority than any existing coro. Changing the priority of the current coro will take effect immediately, but changing the priority of a coro in the ready queue (but not running) will only take effect after the next schedule (of that coro). This is a bug that will be fixed in some future version. $newprio = $coro->nice ($change) Similar to "prio", but subtract the given value from the priority (i.e. higher values mean lower priority, just as in UNIX's nice command). $olddesc = $coro->desc ($newdesc) Sets (or gets in case the argument is missing) the description for this coro thread. This is just a free-form string you can associate with a coro. This method simply sets the "$coro->{desc}" member to the given string. You can modify this member directly if you wish, and in fact, this is often preferred to indicate major processing states that can then be seen for example in a Coro::Debug session: sub my_long_function { local $Coro::current->{desc} = "now in my_long_function"; ... $Coro::current->{desc} = "my_long_function: phase 1"; ... $Coro::current->{desc} = "my_long_function: phase 2"; ... } GLOBAL FUNCTIONS Coro::nready Returns the number of coro that are currently in the ready state, i.e. that can be switched to by calling "schedule" directory or indirectly. The value 0 means that the only runnable coro is the currently running one, so "cede" would have no effect, and "schedule" would cause a deadlock unless there is an idle handler that wakes up some coro. my $guard = Coro::guard { ... } This function still exists, but is deprecated. Please use the "Guard::guard" function instead. unblock_sub { ... } This utility function takes a BLOCK or code reference and "unblocks" it, 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 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. If your handler does not plan to block (e.g. simply sends a message to another coro, or puts some other coro into the ready queue), there is no reason to use "unblock_sub". Note that you also need to use "unblock_sub" for any other callbacks that are indirectly executed by any C-based event loop. For example, when you use a module that uses AnyEvent (and you use Coro::AnyEvent) and it provides callbacks that are the result of some event callback, then you must not block either, or use "unblock_sub". $cb = rouse_cb Create and return a "rouse callback". That's a code reference that, when called, will remember a copy of its arguments and notify the owner coro of the callback. See the next function. @args = rouse_wait [$cb] Wait for the specified rouse callback (or the last one that was created in this coro). As soon as the callback is invoked (or when the callback was invoked before "rouse_wait"), it will return the arguments originally passed to the rouse callback. In scalar context, that means you get the *last* argument, just as if "rouse_wait" had a "return ($a1, $a2, $a3...)" statement at the end. See the section HOW TO WAIT FOR A CALLBACK for an actual usage example. HOW TO WAIT FOR A CALLBACK It is very common for a coro to wait for some callback to be called. This occurs naturally when you use coro in an otherwise event-based program, or when you use event-based libraries. These typically register a callback for some event, and call that callback when the event occurred. In a coro, however, you typically want to just wait for the event, simplyifying things. For example "AnyEvent->child" registers a callback to be called when a specific child has exited: my $child_watcher = AnyEvent->child (pid => $pid, cb => sub { ... }); But from within a coro, you often just want to write this: my $status = wait_for_child $pid; Coro offers two functions specifically designed to make this easy, "rouse_cb" and "rouse_wait". The first function, "rouse_cb", generates and returns a callback that, when invoked, will save its arguments and notify the coro that created the callback. The second function, "rouse_wait", waits for the callback to be called (by calling "schedule" to go to sleep) and returns the arguments originally passed to the callback. Using these functions, it becomes easy to write the "wait_for_child" function mentioned above: sub wait_for_child($) { my ($pid) = @_; my $watcher = AnyEvent->child (pid => $pid, cb => rouse_cb); my ($rpid, $rstatus) = rouse_wait; $rstatus } In the case where "rouse_cb" and "rouse_wait" are not flexible enough, you can roll your own, using "schedule" and "ready": sub wait_for_child($) { my ($pid) = @_; # store the current coro in $current, # and provide result variables for the closure passed to ->child my $current = $Coro::current; my ($done, $rstatus); # pass a closure to ->child my $watcher = AnyEvent->child (pid => $pid, cb => sub { $rstatus = $_[1]; # remember rstatus $done = 1; # mark $rstatus as valid $current->ready; # wake up the waiting thread }); # wait until the closure has been called schedule while !$done; $rstatus } BUGS/LIMITATIONS fork with pthread backend When Coro is compiled using the pthread backend (which isn't recommended but required on many BSDs as their libcs are completely broken), then coro will not survive a fork. There is no known workaround except to fix your libc and use a saner backend. perl process emulation ("threads") This module is not perl-pseudo-thread-safe. You should only ever use this module from the first thread (this requirement might be removed in the future to allow per-thread schedulers, but Coro::State does not yet allow this). I recommend disabling thread support and using processes, as having the windows process emulation enabled under unix roughly halves perl performance, even when not used. Attempts to use threads created in another emulated process will crash ("cleanly", with a null pointer exception). coro switching is not signal safe You must not switch to another coro from within a signal handler (only relevant with %SIG - most event libraries provide safe signals), *unless* you are sure you are not interrupting a Coro function. That means you *MUST NOT* call any function that might "block" the current coro - "cede", "schedule" "Coro::Semaphore->down" or anything that calls those. Everything else, including calling "ready", works. WINDOWS PROCESS EMULATION A great many people seem to be confused about ithreads (for example, Chip Salzenberg called me unintelligent, incapable, stupid and gullible, while in the same mail making rather confused statements about perl ithreads (for example, that memory or files would be shared), showing his lack of understanding of this area - if it is hard to understand for Chip, it is probably not obvious to everybody). What follows is an ultra-condensed version of my talk about threads in scripting languages given on the perl workshop 2009: The so-called "ithreads" were originally implemented for two reasons: first, to (badly) emulate unix processes on native win32 perls, and secondly, to replace the older, real thread model ("5.005-threads"). It does that by using threads instead of OS processes. The difference between processes and threads is that threads share memory (and other state, such as files) between threads within a single process, while processes do not share anything (at least not semantically). That means that modifications done by one thread are seen by others, while modifications by one process are not seen by other processes. The "ithreads" work exactly like that: when creating a new ithreads process, all state is copied (memory is copied physically, files and code is copied logically). Afterwards, it isolates all modifications. On UNIX, the same behaviour can be achieved by using operating system processes, except that UNIX typically uses hardware built into the system to do this efficiently, while the windows process emulation emulates this hardware in software (rather efficiently, but of course it is still much slower than dedicated hardware). As mentioned before, loading code, modifying code, modifying data structures and so on is only visible in the ithreads process doing the modification, not in other ithread processes within the same OS process. This is why "ithreads" do not implement threads for perl at all, only processes. What makes it so bad is that on non-windows platforms, you can actually take advantage of custom hardware for this purpose (as evidenced by the forks module, which gives you the (i-) threads API, just much faster). Sharing data is in the i-threads model is done by transferring data structures between threads using copying semantics, which is very slow - shared data simply does not exist. Benchmarks using i-threads which are communication-intensive show extremely bad behaviour with i-threads (in fact, so bad that Coro, which cannot take direct advantage of multiple CPUs, is often orders of magnitude faster because it shares data using real threads, refer to my talk for details). As summary, i-threads *use* threads to implement processes, while the compatible forks module *uses* processes to emulate, uhm, processes. I-threads slow down every perl program when enabled, and outside of windows, serve no (or little) practical purpose, but disadvantages every single-threaded Perl program. This is the reason that I try to avoid the name "ithreads", as it is misleading as it implies that it implements some kind of thread model for perl, and prefer the name "windows process emulation", which describes the actual use and behaviour of it much better. SEE ALSO Event-Loop integration: Coro::AnyEvent, Coro::EV, Coro::Event. Debugging: Coro::Debug. Support/Utility: Coro::Specific, Coro::Util. Locking and IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, Coro::SemaphoreSet, Coro::RWLock. I/O and Timers: Coro::Timer, Coro::Handle, Coro::Socket, Coro::AIO. Compatibility with other modules: Coro::LWP (but see also AnyEvent::HTTP for a better-working alternative), Coro::BDB, Coro::Storable, Coro::Select. XS API: Coro::MakeMaker. Low level Configuration, Thread Environment, Continuations: Coro::State. AUTHOR/SUPPORT/CONTACT Marc A. Lehmann http://software.schmorp.de/pkg/Coro.html Coro-6.55/Coro/0000755000000000000000000000000013514362055011757 5ustar rootrootCoro-6.55/Coro/ecb.h0000644000000000000000000010531613504246374012673 0ustar rootroot/* * libecb - http://software.schmorp.de/pkg/libecb * * Copyright (©) 2009-2015 Marc Alexander Lehmann * Copyright (©) 2011 Emanuele Giaquinta * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #ifndef ECB_H #define ECB_H /* 16 bits major, 16 bits minor */ #define ECB_VERSION 0x00010006 #ifdef _WIN32 typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; #if __GNUC__ typedef signed long long int64_t; typedef unsigned long long uint64_t; #else /* _MSC_VER || __BORLANDC__ */ typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #endif #ifdef _WIN64 #define ECB_PTRSIZE 8 typedef uint64_t uintptr_t; typedef int64_t intptr_t; #else #define ECB_PTRSIZE 4 typedef uint32_t uintptr_t; typedef int32_t intptr_t; #endif #else #include #if (defined INTPTR_MAX ? INTPTR_MAX : ULONG_MAX) > 0xffffffffU #define ECB_PTRSIZE 8 #else #define ECB_PTRSIZE 4 #endif #endif #define ECB_GCC_AMD64 (__amd64 || __amd64__ || __x86_64 || __x86_64__) #define ECB_MSVC_AMD64 (_M_AMD64 || _M_X64) /* work around x32 idiocy by defining proper macros */ #if ECB_GCC_AMD64 || ECB_MSVC_AMD64 #if _ILP32 #define ECB_AMD64_X32 1 #else #define ECB_AMD64 1 #endif #endif /* many compilers define _GNUC_ to some versions but then only implement * what their idiot authors think are the "more important" extensions, * causing enormous grief in return for some better fake benchmark numbers. * or so. * we try to detect these and simply assume they are not gcc - if they have * an issue with that they should have done it right in the first place. */ #if !defined __GNUC_MINOR__ || defined __INTEL_COMPILER || defined __SUNPRO_C || defined __SUNPRO_CC || defined __llvm__ || defined __clang__ #define ECB_GCC_VERSION(major,minor) 0 #else #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) #endif #define ECB_CLANG_VERSION(major,minor) (__clang_major__ > (major) || (__clang_major__ == (major) && __clang_minor__ >= (minor))) #if __clang__ && defined __has_builtin #define ECB_CLANG_BUILTIN(x) __has_builtin (x) #else #define ECB_CLANG_BUILTIN(x) 0 #endif #if __clang__ && defined __has_extension #define ECB_CLANG_EXTENSION(x) __has_extension (x) #else #define ECB_CLANG_EXTENSION(x) 0 #endif #define ECB_CPP (__cplusplus+0) #define ECB_CPP11 (__cplusplus >= 201103L) #define ECB_CPP14 (__cplusplus >= 201402L) #define ECB_CPP17 (__cplusplus >= 201703L) #if ECB_CPP #define ECB_C 0 #define ECB_STDC_VERSION 0 #else #define ECB_C 1 #define ECB_STDC_VERSION __STDC_VERSION__ #endif #define ECB_C99 (ECB_STDC_VERSION >= 199901L) #define ECB_C11 (ECB_STDC_VERSION >= 201112L) #define ECB_C17 (ECB_STDC_VERSION >= 201710L) #if ECB_CPP #define ECB_EXTERN_C extern "C" #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 */ #if __xlC__ && ECB_CPP #include #endif #if 1400 <= _MSC_VER #include /* fence functions _ReadBarrier, also bit search functions _BitScanReverse */ #endif #ifndef ECB_MEMORY_FENCE #if ECB_GCC_VERSION(2,5) || defined __INTEL_COMPILER || (__llvm__ && __GNUC__) || __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110 #define ECB_MEMORY_FENCE_RELAXED __asm__ __volatile__ ("" : : : "memory") #if __i386 || __i386__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory") #elif ECB_GCC_AMD64 #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mfence" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory") #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory") #elif defined __ARM_ARCH_2__ \ || defined __ARM_ARCH_3__ || defined __ARM_ARCH_3M__ \ || defined __ARM_ARCH_4__ || defined __ARM_ARCH_4T__ \ || defined __ARM_ARCH_5__ || defined __ARM_ARCH_5E__ \ || defined __ARM_ARCH_5T__ || defined __ARM_ARCH_5TE__ \ || defined __ARM_ARCH_5TEJ__ /* should not need any, unless running old code on newer cpu - arm doesn't support that */ #elif defined __ARM_ARCH_6__ || defined __ARM_ARCH_6J__ \ || defined __ARM_ARCH_6K__ || defined __ARM_ARCH_6ZK__ \ || defined __ARM_ARCH_6T2__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory") #elif defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ \ || defined __ARM_ARCH_7R__ || defined __ARM_ARCH_7M__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb" : : : "memory") #elif __aarch64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb ish" : : : "memory") #elif (__sparc || __sparc__) && !(__sparc_v8__ || defined __sparcv8) #define ECB_MEMORY_FENCE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad | #StoreStore | #StoreLoad" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("membar #LoadStore | #StoreStore") #elif defined __s390__ || defined __s390x__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("bcr 15,0" : : : "memory") #elif defined __mips__ /* GNU/Linux emulates sync on mips1 architectures, so we force its use */ /* anybody else who still uses mips1 is supposed to send in their version, with detection code. */ #define ECB_MEMORY_FENCE __asm__ __volatile__ (".set mips2; sync; .set mips0" : : : "memory") #elif defined __alpha__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mb" : : : "memory") #elif defined __hppa__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("") #elif defined __ia64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mf" : : : "memory") #elif defined __m68k__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory") #elif defined __m88k__ #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 */ #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier) #define ECB_MEMORY_FENCE _ReadWriteBarrier () #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */ #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier () #elif defined _WIN32 #include #define ECB_MEMORY_FENCE MemoryBarrier () /* actually just xchg on x86... scary */ #elif __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110 #include #define ECB_MEMORY_FENCE __machine_rw_barrier () #define ECB_MEMORY_FENCE_ACQUIRE __machine_acq_barrier () #define ECB_MEMORY_FENCE_RELEASE __machine_rel_barrier () #define ECB_MEMORY_FENCE_RELAXED __compiler_barrier () #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 #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 #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 !defined ECB_MEMORY_FENCE_RELAXED && defined ECB_MEMORY_FENCE #define ECB_MEMORY_FENCE_RELAXED ECB_MEMORY_FENCE /* very heavy-handed */ #endif /*****************************************************************************/ #if ECB_CPP #define ecb_inline static inline #elif ECB_GCC_VERSION(2,5) #define ecb_inline static __inline__ #elif ECB_C99 #define ecb_inline static inline #else #define ecb_inline static #endif #if ECB_GCC_VERSION(3,3) #define ecb_restrict __restrict__ #elif ECB_C99 #define ecb_restrict restrict #else #define ecb_restrict #endif typedef int ecb_bool; #define ECB_CONCAT_(a, b) a ## b #define ECB_CONCAT(a, b) ECB_CONCAT_(a, b) #define ECB_STRINGIFY_(a) # a #define ECB_STRINGIFY(a) ECB_STRINGIFY_(a) #define ECB_STRINGIFY_EXPR(expr) ((expr), ECB_STRINGIFY_ (expr)) #define ecb_function_ ecb_inline #if ECB_GCC_VERSION(3,1) || ECB_CLANG_VERSION(2,8) #define ecb_attribute(attrlist) __attribute__ (attrlist) #else #define ecb_attribute(attrlist) #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_constant_p) #define ecb_is_constant(expr) __builtin_constant_p (expr) #else /* possible C11 impl for integral types typedef struct ecb_is_constant_struct ecb_is_constant_struct; #define ecb_is_constant(expr) _Generic ((1 ? (struct ecb_is_constant_struct *)0 : (void *)((expr) - (expr)), ecb_is_constant_struct *: 0, default: 1)) */ #define ecb_is_constant(expr) 0 #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_expect) #define ecb_expect(expr,value) __builtin_expect ((expr),(value)) #else #define ecb_expect(expr,value) (expr) #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_prefetch) #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality) #else #define ecb_prefetch(addr,rw,locality) #endif /* no emulation for ecb_decltype */ #if ECB_CPP11 // older implementations might have problems with decltype(x)::type, work around it template struct ecb_decltype_t { typedef T type; }; #define ecb_decltype(x) ecb_decltype_t::type #elif ECB_GCC_VERSION(3,0) || ECB_CLANG_VERSION(2,8) #define ecb_decltype(x) __typeof__ (x) #endif #if _MSC_VER >= 1300 #define ecb_deprecated __declspec (deprecated) #else #define ecb_deprecated ecb_attribute ((__deprecated__)) #endif #if _MSC_VER >= 1500 #define ecb_deprecated_message(msg) __declspec (deprecated (msg)) #elif ECB_GCC_VERSION(4,5) #define ecb_deprecated_message(msg) ecb_attribute ((__deprecated__ (msg)) #else #define ecb_deprecated_message(msg) ecb_deprecated #endif #if _MSC_VER >= 1400 #define ecb_noinline __declspec (noinline) #else #define ecb_noinline ecb_attribute ((__noinline__)) #endif #define ecb_unused ecb_attribute ((__unused__)) #define ecb_const ecb_attribute ((__const__)) #define ecb_pure ecb_attribute ((__pure__)) #if ECB_C11 || __IBMC_NORETURN /* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/language_ref/noreturn.html */ #define ecb_noreturn _Noreturn #elif ECB_CPP11 #define ecb_noreturn [[noreturn]] #elif _MSC_VER >= 1200 /* http://msdn.microsoft.com/en-us/library/k6ktzx3s.aspx */ #define ecb_noreturn __declspec (noreturn) #else #define ecb_noreturn ecb_attribute ((__noreturn__)) #endif #if ECB_GCC_VERSION(4,3) #define ecb_artificial ecb_attribute ((__artificial__)) #define ecb_hot ecb_attribute ((__hot__)) #define ecb_cold ecb_attribute ((__cold__)) #else #define ecb_artificial #define ecb_hot #define ecb_cold #endif /* put around conditional expressions if you are very sure that the */ /* expression is mostly true or mostly false. note that these return */ /* booleans, not the expression. */ #define ecb_expect_false(expr) ecb_expect (!!(expr), 0) #define ecb_expect_true(expr) ecb_expect (!!(expr), 1) /* for compatibility to the rest of the world */ #define ecb_likely(expr) ecb_expect_true (expr) #define ecb_unlikely(expr) ecb_expect_false (expr) /* count trailing zero bits and count # of one bits */ #if ECB_GCC_VERSION(3,4) \ || (ECB_CLANG_BUILTIN(__builtin_clz) && ECB_CLANG_BUILTIN(__builtin_clzll) \ && ECB_CLANG_BUILTIN(__builtin_ctz) && ECB_CLANG_BUILTIN(__builtin_ctzll) \ && ECB_CLANG_BUILTIN(__builtin_popcount)) /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */ #define ecb_ld32(x) (__builtin_clz (x) ^ 31) #define ecb_ld64(x) (__builtin_clzll (x) ^ 63) #define ecb_ctz32(x) __builtin_ctz (x) #define ecb_ctz64(x) __builtin_ctzll (x) #define ecb_popcount32(x) __builtin_popcount (x) /* no popcountll */ #else ecb_function_ ecb_const int ecb_ctz32 (uint32_t x); ecb_function_ ecb_const int ecb_ctz32 (uint32_t x) { #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanForward (&r, x); return (int)r; #else int r = 0; x &= ~x + 1; /* this isolates the lowest bit */ #if ECB_branchless_on_i386 r += !!(x & 0xaaaaaaaa) << 0; r += !!(x & 0xcccccccc) << 1; r += !!(x & 0xf0f0f0f0) << 2; r += !!(x & 0xff00ff00) << 3; r += !!(x & 0xffff0000) << 4; #else if (x & 0xaaaaaaaa) r += 1; if (x & 0xcccccccc) r += 2; if (x & 0xf0f0f0f0) r += 4; if (x & 0xff00ff00) r += 8; if (x & 0xffff0000) r += 16; #endif return r; #endif } ecb_function_ ecb_const int ecb_ctz64 (uint64_t x); ecb_function_ ecb_const int ecb_ctz64 (uint64_t x) { #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanForward64 (&r, x); return (int)r; #else int shift = x & 0xffffffff ? 0 : 32; return ecb_ctz32 (x >> shift) + shift; #endif } ecb_function_ ecb_const int ecb_popcount32 (uint32_t x); ecb_function_ ecb_const int ecb_popcount32 (uint32_t x) { x -= (x >> 1) & 0x55555555; x = ((x >> 2) & 0x33333333) + (x & 0x33333333); x = ((x >> 4) + x) & 0x0f0f0f0f; x *= 0x01010101; return x >> 24; } ecb_function_ ecb_const int ecb_ld32 (uint32_t x); ecb_function_ ecb_const int ecb_ld32 (uint32_t x) { #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanReverse (&r, x); return (int)r; #else int r = 0; if (x >> 16) { x >>= 16; r += 16; } if (x >> 8) { x >>= 8; r += 8; } if (x >> 4) { x >>= 4; r += 4; } if (x >> 2) { x >>= 2; r += 2; } if (x >> 1) { r += 1; } return r; #endif } ecb_function_ ecb_const int ecb_ld64 (uint64_t x); ecb_function_ ecb_const int ecb_ld64 (uint64_t x) { #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanReverse64 (&r, x); return (int)r; #else int r = 0; if (x >> 32) { x >>= 32; r += 32; } return r + ecb_ld32 (x); #endif } #endif ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x); ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x) { return !(x & (x - 1)); } ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x); ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x) { return !(x & (x - 1)); } ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x); ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x) { return ( (x * 0x0802U & 0x22110U) | (x * 0x8020U & 0x88440U)) * 0x10101U >> 16; } ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x); ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x) { x = ((x >> 1) & 0x5555) | ((x & 0x5555) << 1); x = ((x >> 2) & 0x3333) | ((x & 0x3333) << 2); x = ((x >> 4) & 0x0f0f) | ((x & 0x0f0f) << 4); x = ( x >> 8 ) | ( x << 8); return x; } ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x) { x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1); x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2); x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4); x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8); x = ( x >> 16 ) | ( x << 16); return x; } /* popcount64 is only available on 64 bit cpus as gcc builtin */ /* so for this version we are lazy */ ecb_function_ ecb_const int ecb_popcount64 (uint64_t x); ecb_function_ ecb_const int ecb_popcount64 (uint64_t x) { return ecb_popcount32 (x) + ecb_popcount32 (x >> 32); } ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count); ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count); ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count); ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count); ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count); ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count); ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count); ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count); ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); } ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); } ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); } ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); } ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); } ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); } ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); } ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); } #if ECB_GCC_VERSION(4,3) || (ECB_CLANG_BUILTIN(__builtin_bswap32) && ECB_CLANG_BUILTIN(__builtin_bswap64)) #if ECB_GCC_VERSION(4,8) || ECB_CLANG_BUILTIN(__builtin_bswap16) #define ecb_bswap16(x) __builtin_bswap16 (x) #else #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16) #endif #define ecb_bswap32(x) __builtin_bswap32 (x) #define ecb_bswap64(x) __builtin_bswap64 (x) #elif _MSC_VER #include #define ecb_bswap16(x) ((uint16_t)_byteswap_ushort ((uint16_t)(x))) #define ecb_bswap32(x) ((uint32_t)_byteswap_ulong ((uint32_t)(x))) #define ecb_bswap64(x) ((uint64_t)_byteswap_uint64 ((uint64_t)(x))) #else ecb_function_ ecb_const uint16_t ecb_bswap16 (uint16_t x); ecb_function_ ecb_const uint16_t ecb_bswap16 (uint16_t x) { return ecb_rotl16 (x, 8); } ecb_function_ ecb_const uint32_t ecb_bswap32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_bswap32 (uint32_t x) { return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16); } ecb_function_ ecb_const uint64_t ecb_bswap64 (uint64_t x); ecb_function_ ecb_const uint64_t ecb_bswap64 (uint64_t x) { return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32); } #endif #if ECB_GCC_VERSION(4,5) || ECB_CLANG_BUILTIN(__builtin_unreachable) #define ecb_unreachable() __builtin_unreachable () #else /* this seems to work fine, but gcc always emits a warning for it :/ */ ecb_inline ecb_noreturn void ecb_unreachable (void); ecb_inline ecb_noreturn void ecb_unreachable (void) { } #endif /* try to tell the compiler that some condition is definitely true */ #define ecb_assume(cond) if (!(cond)) ecb_unreachable (); else 0 ecb_inline ecb_const uint32_t ecb_byteorder_helper (void); ecb_inline ecb_const uint32_t ecb_byteorder_helper (void) { /* the union code still generates code under pressure in gcc, */ /* but less than using pointers, and always seems to */ /* successfully return a constant. */ /* the reason why we have this horrible preprocessor mess */ /* is to avoid it in all cases, at least on common architectures */ /* or when using a recent enough gcc version (>= 4.6) */ #if (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \ || ((__i386 || __i386__ || _M_IX86 || ECB_GCC_AMD64 || ECB_MSVC_AMD64) && !__VOS__) #define ECB_LITTLE_ENDIAN 1 return 0x44332211; #elif (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) \ || ((__AARCH64EB__ || __MIPSEB__ || __ARMEB__) && !__VOS__) #define ECB_BIG_ENDIAN 1 return 0x11223344; #else union { uint8_t c[4]; uint32_t u; } u = { 0x11, 0x22, 0x33, 0x44 }; return u.u; #endif } ecb_inline ecb_const ecb_bool ecb_big_endian (void); ecb_inline ecb_const ecb_bool ecb_big_endian (void) { return ecb_byteorder_helper () == 0x11223344; } ecb_inline ecb_const ecb_bool ecb_little_endian (void); ecb_inline ecb_const ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44332211; } #if ECB_GCC_VERSION(3,0) || ECB_C99 #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0)) #else #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n))) #endif #if ECB_CPP template static inline T ecb_div_rd (T val, T div) { return val < 0 ? - ((-val + div - 1) / div) : (val ) / div; } template static inline T ecb_div_ru (T val, T div) { return val < 0 ? - ((-val ) / div) : (val + div - 1) / div; } #else #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val) ) / (div)) #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val) ) / (div)) : ((val) + (div) - 1) / (div)) #endif #if ecb_cplusplus_does_not_suck /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */ template static inline int ecb_array_length (const T (&arr)[N]) { return N; } #else #define ecb_array_length(name) (sizeof (name) / sizeof (name [0])) #endif ecb_function_ ecb_const uint32_t ecb_binary16_to_binary32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_binary16_to_binary32 (uint32_t x) { unsigned int s = (x & 0x8000) << (31 - 15); int e = (x >> 10) & 0x001f; unsigned int m = x & 0x03ff; if (ecb_expect_false (e == 31)) /* infinity or NaN */ e = 255 - (127 - 15); else if (ecb_expect_false (!e)) { if (ecb_expect_true (!m)) /* zero, handled by code below by forcing e to 0 */ e = 0 - (127 - 15); else { /* subnormal, renormalise */ unsigned int s = 10 - ecb_ld32 (m); m = (m << s) & 0x3ff; /* mask implicit bit */ e -= s - 1; } } /* e and m now are normalised, or zero, (or inf or nan) */ e += 127 - 15; return s | (e << 23) | (m << (23 - 10)); } ecb_function_ ecb_const uint16_t ecb_binary32_to_binary16 (uint32_t x); ecb_function_ ecb_const uint16_t ecb_binary32_to_binary16 (uint32_t x) { unsigned int s = (x >> 16) & 0x00008000; /* sign bit, the easy part */ unsigned int e = ((x >> 23) & 0x000000ff) - (127 - 15); /* the desired exponent */ unsigned int m = x & 0x007fffff; x &= 0x7fffffff; /* if it's within range of binary16 normals, use fast path */ if (ecb_expect_true (0x38800000 <= x && x <= 0x477fefff)) { /* mantissa round-to-even */ m += 0x00000fff + ((m >> (23 - 10)) & 1); /* handle overflow */ if (ecb_expect_false (m >= 0x00800000)) { m >>= 1; e += 1; } return s | (e << 10) | (m >> (23 - 10)); } /* handle large numbers and infinity */ if (ecb_expect_true (0x477fefff < x && x <= 0x7f800000)) return s | 0x7c00; /* handle zero, subnormals and small numbers */ if (ecb_expect_true (x < 0x38800000)) { /* zero */ if (ecb_expect_true (!x)) return s; /* handle subnormals */ /* too small, will be zero */ if (e < (14 - 24)) /* might not be sharp, but is good enough */ return s; m |= 0x00800000; /* make implicit bit explicit */ /* very tricky - we need to round to the nearest e (+10) bit value */ { unsigned int bits = 14 - e; unsigned int half = (1 << (bits - 1)) - 1; unsigned int even = (m >> bits) & 1; /* if this overflows, we will end up with a normalised number */ m = (m + half + even) >> bits; } return s | m; } /* handle NaNs, preserve leftmost nan bits, but make sure we don't turn them into infinities */ m >>= 13; return s | 0x7c00 | m | !m; } /*******************************************************************************/ /* floating point stuff, can be disabled by defining ECB_NO_LIBM */ /* basically, everything uses "ieee pure-endian" floating point numbers */ /* the only noteworthy exception is ancient armle, which uses order 43218765 */ #if 0 \ || __i386 || __i386__ \ || ECB_GCC_AMD64 \ || __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ \ || defined __s390__ || defined __s390x__ \ || defined __mips__ \ || defined __alpha__ \ || defined __hppa__ \ || defined __ia64__ \ || defined __m68k__ \ || defined __m88k__ \ || defined __sh__ \ || defined _M_IX86 || defined ECB_MSVC_AMD64 || defined _M_IA64 \ || (defined __arm__ && (defined __ARM_EABI__ || defined __EABI__ || defined __VFP_FP__ || defined _WIN32_WCE || defined __ANDROID__)) \ || defined __aarch64__ #define ECB_STDFP 1 #include /* for memcpy */ #else #define ECB_STDFP 0 #endif #ifndef ECB_NO_LIBM #include /* for frexp*, ldexp*, INFINITY, NAN */ /* only the oldest of old doesn't have this one. solaris. */ #ifdef INFINITY #define ECB_INFINITY INFINITY #else #define ECB_INFINITY HUGE_VAL #endif #ifdef NAN #define ECB_NAN NAN #else #define ECB_NAN ECB_INFINITY #endif #if ECB_C99 || _XOPEN_VERSION >= 600 || _POSIX_VERSION >= 200112L #define ecb_ldexpf(x,e) ldexpf ((x), (e)) #define ecb_frexpf(x,e) frexpf ((x), (e)) #else #define ecb_ldexpf(x,e) (float) ldexp ((double) (x), (e)) #define ecb_frexpf(x,e) (float) frexp ((double) (x), (e)) #endif /* convert a float to ieee single/binary32 */ ecb_function_ ecb_const uint32_t ecb_float_to_binary32 (float x); ecb_function_ ecb_const uint32_t ecb_float_to_binary32 (float x) { uint32_t r; #if ECB_STDFP memcpy (&r, &x, 4); #else /* slow emulation, works for anything but -0 */ uint32_t m; int e; if (x == 0e0f ) return 0x00000000U; if (x > +3.40282346638528860e+38f) return 0x7f800000U; if (x < -3.40282346638528860e+38f) return 0xff800000U; if (x != x ) return 0x7fbfffffU; m = ecb_frexpf (x, &e) * 0x1000000U; r = m & 0x80000000U; if (r) m = -m; if (e <= -126) { m &= 0xffffffU; m >>= (-125 - e); e = -126; } r |= (e + 126) << 23; r |= m & 0x7fffffU; #endif return r; } /* converts an ieee single/binary32 to a float */ ecb_function_ ecb_const float ecb_binary32_to_float (uint32_t x); ecb_function_ ecb_const float ecb_binary32_to_float (uint32_t x) { float r; #if ECB_STDFP memcpy (&r, &x, 4); #else /* emulation, only works for normals and subnormals and +0 */ int neg = x >> 31; int e = (x >> 23) & 0xffU; x &= 0x7fffffU; if (e) x |= 0x800000U; else e = 1; /* we distrust ldexpf a bit and do the 2**-24 scaling by an extra multiply */ r = ecb_ldexpf (x * (0.5f / 0x800000U), e - 126); r = neg ? -r : r; #endif return r; } /* convert a double to ieee double/binary64 */ ecb_function_ ecb_const uint64_t ecb_double_to_binary64 (double x); ecb_function_ ecb_const uint64_t ecb_double_to_binary64 (double x) { uint64_t r; #if ECB_STDFP memcpy (&r, &x, 8); #else /* slow emulation, works for anything but -0 */ uint64_t m; int e; if (x == 0e0 ) return 0x0000000000000000U; if (x > +1.79769313486231470e+308) return 0x7ff0000000000000U; if (x < -1.79769313486231470e+308) return 0xfff0000000000000U; if (x != x ) return 0X7ff7ffffffffffffU; m = frexp (x, &e) * 0x20000000000000U; r = m & 0x8000000000000000;; if (r) m = -m; if (e <= -1022) { m &= 0x1fffffffffffffU; m >>= (-1021 - e); e = -1022; } r |= ((uint64_t)(e + 1022)) << 52; r |= m & 0xfffffffffffffU; #endif return r; } /* converts an ieee double/binary64 to a double */ ecb_function_ ecb_const double ecb_binary64_to_double (uint64_t x); ecb_function_ ecb_const double ecb_binary64_to_double (uint64_t x) { double r; #if ECB_STDFP memcpy (&r, &x, 8); #else /* emulation, only works for normals and subnormals and +0 */ int neg = x >> 63; int e = (x >> 52) & 0x7ffU; x &= 0xfffffffffffffU; if (e) x |= 0x10000000000000U; else e = 1; /* we distrust ldexp a bit and do the 2**-53 scaling by an extra multiply */ r = ldexp (x * (0.5 / 0x10000000000000U), e - 1022); r = neg ? -r : r; #endif return r; } /* convert a float to ieee half/binary16 */ ecb_function_ ecb_const uint16_t ecb_float_to_binary16 (float x); ecb_function_ ecb_const uint16_t ecb_float_to_binary16 (float x) { return ecb_binary32_to_binary16 (ecb_float_to_binary32 (x)); } /* convert an ieee half/binary16 to float */ ecb_function_ ecb_const float ecb_binary16_to_float (uint16_t x); ecb_function_ ecb_const float ecb_binary16_to_float (uint16_t x) { return ecb_binary32_to_float (ecb_binary16_to_binary32 (x)); } #endif #endif Coro-6.55/Coro/Socket.pm0000644000000000000000000001253713514360741013555 0ustar rootroot=head1 NAME Coro::Socket - non-blocking socket-I/O =head1 SYNOPSIS use Coro::Socket; # listen on an ipv4 socket my $socket = new Coro::Socket PeerHost => "localhost", PeerPort => 'finger'; # listen on any other type of socket my $socket = Coro::Socket->new_from_fh (IO::Socket::UNIX->new Local => "/tmp/socket", Type => SOCK_STREAM, ); =head1 DESCRIPTION This module is an L user, you need to make sure that you use and run a supported event loop. This module implements socket-handles in a coroutine-compatible way, that is, other coroutines can run while reads or writes block on the handle. See L, especially the note about prefering method calls. =head1 IPV6 WARNING This module was written to imitate the L API, and derive from it. Since IO::Socket::INET does not support IPv6, this module does neither. Therefore it is not recommended to use Coro::Socket in new code. Instead, use L and L, e.g.: use Coro; use Coro::Handle; use AnyEvent::Socket; # use tcp_connect from AnyEvent::Socket # and call Coro::Handle::unblock on it. tcp_connect "www.google.com", 80, Coro::rouse_cb; my $fh = unblock +(Coro::rouse_wait)[0]; # now we have a perfectly thread-safe socket handle in $fh print $fh "GET / HTTP/1.0\015\012\015\012"; local $/; print <$fh>; Using C gives you transparent IPv6, multi-homing, SRV-record etc. support. For listening sockets, use C. =over 4 =cut package Coro::Socket; use common::sense; use Errno (); use Carp qw(croak); use Socket; use IO::Socket::INET (); use Coro::Util (); use base qw(Coro::Handle IO::Socket::INET); our $VERSION = 6.55; our (%_proto, %_port); sub _proto($) { $_proto{$_[0]} ||= do { ((getprotobyname $_[0])[2] || (getprotobynumber $_[0])[2]) or croak "unsupported protocol: $_[0]"; }; } sub _port($$) { $_port{$_[0],$_[1]} ||= do { return $_[0] if $_[0] =~ /^\d+$/; $_[0] =~ /([^(]+)\s*(?:\((\d+)\))?/x or croak "unparsable port number: $_[0]"; ((getservbyname $1, $_[1])[2] || (getservbyport $1, $_[1])[2] || $2) or croak "unknown port: $_[0]"; }; } sub _sa($$$) { my ($host, $port, $proto) = @_; $port or $host =~ s/:([^:]+)$// and $port = $1; my $_proto = _proto($proto); my $_port = _port($port, $proto); my $_host = Coro::Util::inet_aton $host or croak "$host: unable to resolve"; pack_sockaddr_in $_port, $_host } =item $fh = new Coro::Socket param => value, ... Create a new non-blocking tcp handle and connect to the given host and port. The parameter names and values are mostly the same as for IO::Socket::INET (as ugly as I think they are). The parameters officially supported currently are: C, C, C, C, C, C, C, C, C. $fh = new Coro::Socket PeerHost => "localhost", PeerPort => 'finger'; =cut sub _prepare_socket { my ($self, $arg) = @_; $self } sub new { my ($class, %arg) = @_; $arg{Proto} ||= 'tcp'; $arg{LocalHost} ||= delete $arg{LocalAddr}; $arg{PeerHost} ||= delete $arg{PeerAddr}; defined ($arg{Type}) or $arg{Type} = $arg{Proto} eq "tcp" ? SOCK_STREAM : SOCK_DGRAM; socket my $fh, PF_INET, $arg{Type}, _proto ($arg{Proto}) or return; my $self = bless Coro::Handle->new_from_fh ( $fh, timeout => $arg{Timeout}, forward_class => $arg{forward_class}, partial => $arg{partial}, ), $class or return; $self->configure (\%arg) } sub configure { my ($self, $arg) = @_; if ($arg->{ReuseAddr}) { $self->setsockopt (SOL_SOCKET, SO_REUSEADDR, 1) or croak "setsockopt(SO_REUSEADDR): $!"; } if ($arg->{ReusePort}) { $self->setsockopt (SOL_SOCKET, SO_REUSEPORT, 1) or croak "setsockopt(SO_REUSEPORT): $!"; } if ($arg->{Broadcast}) { $self->setsockopt (SOL_SOCKET, SO_BROADCAST, 1) or croak "setsockopt(SO_BROADCAST): $!"; } if ($arg->{SO_RCVBUF}) { $self->setsockopt (SOL_SOCKET, SO_RCVBUF, $arg->{SO_RCVBUF}) or croak "setsockopt(SO_RCVBUF): $!"; } if ($arg->{SO_SNDBUF}) { $self->setsockopt (SOL_SOCKET, SO_SNDBUF, $arg->{SO_SNDBUF}) or croak "setsockopt(SO_SNDBUF): $!"; } if ($arg->{LocalPort} || $arg->{LocalHost}) { my @sa = _sa($arg->{LocalHost} || "0.0.0.0", $arg->{LocalPort} || 0, $arg->{Proto}); $self->bind ($sa[0]) or croak "bind($arg->{LocalHost}:$arg->{LocalPort}): $!"; } if ($arg->{PeerHost}) { my @sa = _sa ($arg->{PeerHost}, $arg->{PeerPort}, $arg->{Proto}); for (@sa) { $! = 0; if ($self->connect ($_)) { next unless writable $self; $! = unpack "i", $self->getsockopt (SOL_SOCKET, SO_ERROR); } $! or last; $!{ECONNREFUSED} or $!{ENETUNREACH} or $!{ETIMEDOUT} or $!{EHOSTUNREACH} or return; } } elsif (exists $arg->{Listen}) { $self->listen ($arg->{Listen}) or return; } $self } 1; =back =head1 AUTHOR/SUPPORT/CONTACT Marc A. Lehmann http://software.schmorp.de/pkg/Coro.html =cut Coro-6.55/Coro/Util.pm0000644000000000000000000001267713514360741013247 0ustar rootroot=head1 NAME Coro::Util - various utility functions. =head1 SYNOPSIS use Coro::Util; =head1 DESCRIPTION This module implements various utility functions, mostly replacing perl functions by non-blocking counterparts. Many of these functions exist for the sole purpose of emulating existing interfaces, no matter how bad or limited they are (e.g. no IPv6 support). This module is an AnyEvent user. Refer to the L documentation to see how to integrate it into your own programs. =over 4 =cut package Coro::Util; use common::sense; use Socket (); use AnyEvent (); use AnyEvent::Socket (); use Coro::State; use Coro::Handle; use Coro::Storable (); use Coro::AnyEvent (); use Coro::Semaphore; use base 'Exporter'; our @EXPORT = qw(gethostbyname gethostbyaddr); our @EXPORT_OK = qw(inet_aton fork_eval); our $VERSION = 6.55; our $MAXPARALLEL = 16; # max. number of parallel jobs my $jobs = new Coro::Semaphore $MAXPARALLEL; sub _do_asy(&;@) { my $sub = shift; $jobs->down; my $fh; my $pid = open $fh, "-|"; if (!defined $pid) { die "fork: $!"; } elsif (!$pid) { syswrite STDOUT, join "\0", map { unpack "H*", $_ } &$sub; Coro::Util::_exit 0; } my $buf; my $wakeup = Coro::rouse_cb; my $w; $w = AE::io $fh, 0, sub { sysread $fh, $buf, 16384, length $buf and return; undef $w; $wakeup->(); }; Coro::rouse_wait; $jobs->up; my @r = map { pack "H*", $_ } split /\0/, $buf; wantarray ? @r : $r[0]; } =item $ipn = Coro::Util::inet_aton $hostname || $ip Works almost exactly like its C counterpart, except that it does not block other coroutines. Does not handle multihomed hosts or IPv6 - consider using C with the L rouse functions instead. =cut sub inet_aton { AnyEvent::Socket::inet_aton $_[0], Coro::rouse_cb; (grep length == 4, Coro::rouse_wait)[0] } =item gethostbyname, gethostbyaddr Work similarly to their Perl counterparts, but do not block. Uses C internally. Does not handle multihomed hosts or IPv6 - consider using C or C with the L rouse functions instead. =cut sub gethostbyname($) { AnyEvent::Socket::inet_aton $_[0], Coro::rouse_cb; ($_[0], $_[0], &Socket::AF_INET, 4, map +(AnyEvent::Socket::format_address $_), grep length == 4, Coro::rouse_wait) } sub gethostbyaddr($$) { _do_asy { gethostbyaddr $_[0], $_[1] } @_ } =item @result = Coro::Util::fork_eval { ... }, @args Executes the given code block or code reference with the given arguments in a separate process, returning the results. The return values must be serialisable with Coro::Storable. It may, of course, block. Note that using event handling in the sub is not usually a good idea as you will inherit a mixed set of watchers from the parent. Exceptions will be correctly forwarded to the caller. This function is useful for pushing cpu-intensive computations into a different process, for example to take advantage of multiple CPU's. Its also useful if you want to simply run some blocking functions (such as C) and do not care about the overhead enough to code your own pid watcher etc. This function might keep a pool of processes in some future version, as fork can be rather slow in large processes. You should also look at C, which is newer and more compatible to totally broken Perl implementations such as the one from ActiveState. Example: execute some external program (convert image to rgba raw form) and add a long computation (extract the alpha channel) in a separate process, making sure that never more then $NUMCPUS processes are being run. my $cpulock = new Coro::Semaphore $NUMCPUS; sub do_it { my ($path) = @_; my $guard = $cpulock->guard; Coro::Util::fork_eval { open my $fh, "convert -depth 8 \Q$path\E rgba:" or die "$path: $!"; local $/; # make my eyes hurt pack "C*", unpack "(xxxC)*", <$fh> } } my $alphachannel = do_it "/tmp/img.png"; =cut sub fork_eval(&@) { my ($cb, @args) = @_; pipe my $fh1, my $fh2 or die "pipe: $!"; my $pid = fork; if ($pid) { undef $fh2; my $res = Coro::Storable::thaw +(Coro::Handle::unblock $fh1)->readline (undef); waitpid $pid, 0; # should not block, we expect the child to simply behave die $$res unless "ARRAY" eq ref $res; return wantarray ? @$res : $res->[-1]; } elsif (defined $pid) { delete $SIG{__WARN__}; delete $SIG{__DIE__}; # just in case, this hack effectively disables event processing # in the child. cleaner and slower would be to canceling all # event watchers, but we are event-model agnostic. undef $Coro::idle; $Coro::current->prio (Coro::PRIO_MAX); eval { undef $fh1; my @res = eval { $cb->(@args) }; open my $fh, ">", \my $buf or die "fork_eval: cannot open fh-to-buf in child: $!"; Storable::store_fd $@ ? \"$@" : \@res, $fh; close $fh; syswrite $fh2, $buf; close $fh2; }; warn $@ if $@; Coro::Util::_exit 0; } else { die "fork_eval: $!"; } } # make sure store_fd is preloaded eval { Storable::store_fd undef, undef }; 1; =back =head1 AUTHOR/SUPPORT/CONTACT Marc A. Lehmann http://software.schmorp.de/pkg/Coro.html =cut Coro-6.55/Coro/Channel.pm0000644000000000000000000000772513514360741013700 0ustar rootroot=head1 NAME Coro::Channel - message queues =head1 SYNOPSIS use Coro; $q1 = new Coro::Channel ; $q1->put ("xxx"); print $q1->get; die unless $q1->size; =head1 DESCRIPTION A Coro::Channel is the equivalent of a unix pipe (and similar to amiga message ports): you can put things into it on one end and read things out of it from the other end. If the capacity of the Channel is maxed out writers will block. Both ends of a Channel can be read/written from by as many coroutines as you want concurrently. You don't have to load C manually, it will be loaded automatically when you C and call the C constructor. =over 4 =cut package Coro::Channel; use common::sense; use Coro (); use Coro::Semaphore (); our $VERSION = 6.55; sub DATA (){ 0 } sub SGET (){ 1 } sub SPUT (){ 2 } =item $q = new Coro:Channel $maxsize Create a new channel with the given maximum size (practically unlimited if C is omitted or zero). Giving a size of one gives you a traditional channel, i.e. a queue that can store only a single element (which means there will be no buffering, and C will wait until there is a corresponding C call). To buffer one element you have to specify C<2>, and so on. =cut sub new { # we cheat and set infinity == 2*10**9 bless [ [], # initially empty (Coro::Semaphore::_alloc 0), # counts data (Coro::Semaphore::_alloc +($_[1] || 2_000_000_000) - 1), # counts remaining space ] } =item $q->put ($scalar) Put the given scalar into the queue. =cut sub put { push @{$_[0][DATA]}, $_[1]; Coro::Semaphore::up $_[0][SGET]; Coro::Semaphore::down $_[0][SPUT]; } =item $q->get Return the next element from the queue, waiting if necessary. =cut sub get { Coro::Semaphore::down $_[0][SGET]; Coro::Semaphore::up $_[0][SPUT]; shift @{$_[0][DATA]} } =item $q->shutdown Shuts down the Channel by pushing a virtual end marker onto it: This changes the behaviour of the Channel when it becomes or is empty to return C, almost as if infinitely many C elements had been put into the queue. Specifically, this function wakes up any pending C calls and lets them return C, the same on future C calls. C will return the real number of stored elements, though. Another way to describe the behaviour is that C calls will not block when the queue becomes empty but immediately return C. This means that calls to C will work normally and the data will be returned on subsequent C calls. This method is useful to signal the end of data to any consumers, quite similar to an end of stream on e.g. a tcp socket: You have one or more producers that C data into the Channel and one or more consumers who C them. When all producers have finished producing data, a call to C signals this fact to any consumers. A common implementation uses one or more threads that C from a channel until it returns C. To clean everything up, first C the channel, then C the threads. =cut sub shutdown { Coro::Semaphore::adjust $_[0][SGET], 1_000_000_000; } =item $q->size Return the number of elements waiting to be consumed. Please note that: if ($q->size) { my $data = $q->get; ... } is I a race condition but instead works just fine. Note that the number of elements that wait can be larger than C<$maxsize>, as it includes any coroutines waiting to put data into the channel (but not any shutdown condition). This means that the number returned is I the number of calls to C that will succeed instantly and return some data. Calling C has no effect on this number. =cut sub size { scalar @{$_[0][DATA]} } # this is not undocumented by accident - if it breaks, you # get to keep the pieces sub adjust { Coro::Semaphore::adjust $_[0][SPUT], $_[1]; } 1; =back =head1 AUTHOR/SUPPORT/CONTACT Marc A. Lehmann http://software.schmorp.de/pkg/Coro.html =cut Coro-6.55/Coro/Debug.pm0000644000000000000000000004011113514360741013340 0ustar rootroot=head1 NAME Coro::Debug - various functions that help debugging Coro programs =head1 SYNOPSIS use Coro::Debug; our $server = new_unix_server Coro::Debug "/tmp/socketpath"; $ socat readline unix:/tmp/socketpath =head1 DESCRIPTION This module is an L user, you need to make sure that you use and run a supported event loop. This module provides some debugging facilities. Most will, if not handled carefully, severely compromise the security of your program, so use it only for debugging (or take other precautions). It mainly implements a very primitive debugger that is very easy to integrate in your program: our $server = new_unix_server Coro::Debug "/tmp/somepath"; # see new_unix_server, below, for more info It lets you list running coroutines: state (rUnning, Ready, New or neither) |cctx allocated || resident set size (octets) || | scheduled this many times > ps || | | PID SC RSS USES Description Where 14572344 UC 62k 128k [main::] [dm-support.ext:47] 14620056 -- 2260 13 [coro manager] [Coro.pm:358] 14620128 -- 2260 166 [unblock_sub scheduler] [Coro.pm:358] 17764008 N- 152 0 [EV idle process] - 13990784 -- 2596 10k timeslot manager [cf.pm:454] 81424176 -- 18k 4758 [async pool idle] [Coro.pm:257] 23513336 -- 2624 1 follow handler [follow.ext:52] 40548312 -- 15k 5597 player scheduler [player-scheduler.ext:13] 29138032 -- 2548 431 music scheduler [player-env.ext:77] 43449808 -- 2260 3493 worldmap updater [item-worldmap.ext:115] 33352488 -- 19k 2845 [async pool idle] [Coro.pm:257] 81530072 -- 13k 43k map scheduler [map-scheduler.ext:65] 30751144 -- 15k 2204 [async pool idle] [Coro.pm:257] Lets you do backtraces on about any coroutine: > bt 18334288 coroutine is at /opt/cf/ext/player-env.ext line 77 eval {...} called at /opt/cf/ext/player-env.ext line 77 ext::player_env::__ANON__ called at -e line 0 Coro::_run_coro called at -e line 0 Or lets you eval perl code: > 5+7 12 Or lets you eval perl code within other coroutines: > eval 18334288 caller(1); $DB::args[0]->method 1 It can also trace subroutine entry/exits for most coroutines (those not having recursed into a C function), resulting in output similar to: > loglevel 5 > trace 94652688 2007-09-27Z20:30:25.1368 (5) [94652688] enter Socket::sockaddr_in with (8481,\x{7f}\x{00}\x{00}\x{01}) 2007-09-27Z20:30:25.1369 (5) [94652688] leave Socket::sockaddr_in returning (\x{02}\x{00}...) 2007-09-27Z20:30:25.1370 (5) [94652688] enter Net::FCP::Util::touc with (client_get) 2007-09-27Z20:30:25.1371 (5) [94652688] leave Net::FCP::Util::touc returning (ClientGet) 2007-09-27Z20:30:25.1372 (5) [94652688] enter AnyEvent::Impl::Event::io with (AnyEvent,fh,GLOB(0x9256250),poll,w,cb,CODE(0x8c963a0)) 2007-09-27Z20:30:25.1373 (5) [94652688] enter Event::Watcher::__ANON__ with (Event,poll,w,fd,GLOB(0x9256250),cb,CODE(0x8c963a0)) 2007-09-27Z20:30:25.1374 (5) [94652688] enter Event::io::new with (Event::io,poll,w,fd,GLOB(0x9256250),cb,CODE(0x8c963a0)) 2007-09-27Z20:30:25.1375 (5) [94652688] enter Event::Watcher::init with (Event::io=HASH(0x8bfb120),HASH(0x9b7940)) If your program uses the Coro::Debug::log facility: Coro::Debug::log 0, "important message"; Coro::Debug::log 9, "unimportant message"; Then you can even receive log messages in any debugging session: > loglevel 5 2007-09-26Z02:22:46 (9) unimportant message Other commands are available in the shell, use the C command for a list. =head1 FUNCTIONS None of the functions are being exported. =over 4 =cut package Coro::Debug; use common::sense; use overload (); use Carp (); use Scalar::Util (); use Guard; use AnyEvent (); use AnyEvent::Util (); use AnyEvent::Socket (); use Coro (); use Coro::Handle (); use Coro::State (); use Coro::AnyEvent (); use Coro::Timer (); our $VERSION = 6.55; our %log; our $SESLOGLEVEL = exists $ENV{PERL_CORO_DEFAULT_LOGLEVEL} ? $ENV{PERL_CORO_DEFAULT_LOGLEVEL} : -1; our $ERRLOGLEVEL = exists $ENV{PERL_CORO_STDERR_LOGLEVEL} ? $ENV{PERL_CORO_STDERR_LOGLEVEL} : -1; sub find_coro { my ($pid) = @_; if (my ($coro) = grep $_ == $pid, Coro::State::list) { $coro } else { print "$pid: no such coroutine\n"; undef } } sub format_msg($$) { my ($time, $micro) = Coro::Util::gettimeofday; my ($sec, $min, $hour, $day, $mon, $year) = gmtime $time; my $date = sprintf "%04d-%02d-%02dZ%02d:%02d:%02d.%04d", $year + 1900, $mon + 1, $day, $hour, $min, $sec, $micro / 100; sprintf "%s (%d) %s", $date, $_[0], $_[1] } sub format_num4($) { my ($v) = @_; return sprintf "%4d" , $v if $v < 1e4; # 1e5 redundant return sprintf "%3.0fk", $v / 1_000 if $v < 1e6; return sprintf "%1.1fM", $v / 1_000_000 if $v < 1e7 * .995; return sprintf "%3.0fM", $v / 1_000_000 if $v < 1e9; return sprintf "%1.1fG", $v / 1_000_000_000 if $v < 1e10 * .995; return sprintf "%3.0fG", $v / 1_000_000_000 if $v < 1e12; return sprintf "%1.1fT", $v / 1_000_000_000_000 if $v < 1e13 * .995; return sprintf "%3.0fT", $v / 1_000_000_000_000 if $v < 1e15; "++++" } =item log $level, $msg Log a debug message of the given severity level (0 is highest, higher is less important) to all interested parties. =item stderr_loglevel $level Set the loglevel for logging to stderr (defaults to the value of the environment variable PERL_CORO_STDERR_LOGLEVEL, or -1 if missing). =item session_loglevel $level Set the default loglevel for new coro debug sessions (defaults to the value of the environment variable PERL_CORO_DEFAULT_LOGLEVEL, or -1 if missing). =cut sub log($$) { my ($level, $msg) = @_; $msg =~ s/\s*$/\n/; $_->($level, $msg) for values %log; printf STDERR format_msg $level, $msg if $level <= $ERRLOGLEVEL; } sub session_loglevel($) { $SESLOGLEVEL = shift; } sub stderr_loglevel($) { $ERRLOGLEVEL = shift; } =item trace $coro, $loglevel Enables tracing the given coroutine at the given loglevel. If loglevel is omitted, use 5. If coro is omitted, trace the current coroutine. Tracing incurs a very high runtime overhead. It is not uncommon to enable tracing on oneself by simply calling C. A message will be logged at the given loglevel if it is not possible to enable tracing. =item untrace $coro Disables tracing on the given coroutine. =cut sub trace { my ($coro, $loglevel) = @_; $coro ||= $Coro::current; $loglevel = 5 unless defined $loglevel; (Coro::async { if (eval { Coro::State::trace $coro, Coro::State::CC_TRACE | Coro::State::CC_TRACE_SUB; 1 }) { Coro::Debug::log $loglevel, sprintf "[%d] tracing enabled", $coro + 0; $coro->{_trace_line_cb} = sub { Coro::Debug::log $loglevel, sprintf "[%d] at %s:%d\n", $Coro::current+0, @_; }; $coro->{_trace_sub_cb} = sub { Coro::Debug::log $loglevel, sprintf "[%d] %s %s %s\n", $Coro::current+0, $_[0] ? "enter" : "leave", $_[1], $_[2] ? ($_[0] ? "with (" : "returning (") . ( join ",", map { my $x = ref $_ ? overload::StrVal $_ : $_; (substr $x, 40) = "..." if 40 + 3 < length $x; $x =~ s/([^\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02x}", ord $1/ge; $x } @{$_[2]} ) . ")" : ""; }; undef $coro; # the subs keep a reference which we do not want them to do } else { Coro::Debug::log $loglevel, sprintf "[%d] unable to enable tracing: %s", $Coro::current + 0, $@; } })->prio (Coro::PRIO_MAX); Coro::cede; } sub untrace { my ($coro) = @_; $coro ||= $Coro::current; (Coro::async { Coro::State::trace $coro, 0; delete $coro->{_trace_sub_cb}; delete $coro->{_trace_line_cb}; })->prio (Coro::PRIO_MAX); Coro::cede; } sub ps_listing { my $times = Coro::State::enable_times; my $flags = $1; my $verbose = $flags =~ /v/; my $desc_format = $flags =~ /w/ ? "%-24s" : "%-24.24s"; my $tim0_format = $times ? " %9s %8s " : " "; my $tim1_format = $times ? " %9.3f %8.3f " : " "; my $buf = sprintf "%20s %s%s %4s %4s$tim0_format$desc_format %s\n", "PID", "S", "C", "RSS", "USES", $times ? ("t_real", "t_cpu") : (), "Description", "Where"; for my $coro (reverse Coro::State::list) { my @bt; Coro::State::call ($coro, sub { # we try to find *the* definite frame that gives most useful info # by skipping Coro frames and pseudo-frames. for my $frame (1..10) { my @frame = caller $frame; @bt = @frame if $frame[2]; last unless $bt[0] =~ /^Coro/; } }); $bt[1] =~ s/^.*[\/\\]// if @bt && !$verbose; $buf .= sprintf "%20s %s%s %4s %4s$tim1_format$desc_format %s\n", $coro+0, $coro->is_new ? "N" : $coro->is_running ? "U" : $coro->is_ready ? "R" : "-", $coro->is_traced ? "T" : $coro->has_cctx ? "C" : "-", format_num4 $coro->rss, format_num4 $coro->usecount, $times ? $coro->times : (), $coro->debug_desc, (@bt ? sprintf "[%s:%d]", $bt[1], $bt[2] : "-"); } $buf } =item command $string Execute a debugger command, sending any output to STDOUT. Used by C, below. =cut sub command($) { my ($cmd) = @_; $cmd =~ s/\s+$//; if ($cmd =~ /^ps (?:\s* (\S+))? $/x) { print ps_listing; } elsif ($cmd =~ /^bt\s+(\d+)$/) { if (my $coro = find_coro $1) { my $bt; Coro::State::call ($coro, sub { local $Carp::CarpLevel = 2; $bt = eval { Carp::longmess "coroutine is" } || "$@"; }); if ($bt) { print $bt; } else { print "$1: unable to get backtrace\n"; } } } elsif ($cmd =~ /^(?:e|eval)\s+(\d+)\s+(.*)$/) { if (my $coro = find_coro $1) { my $cmd = eval "sub { $2 }"; my @res; Coro::State::call ($coro, sub { @res = eval { &$cmd } }); print $@ ? $@ : (join " ", @res, "\n"); } } elsif ($cmd =~ /^(?:tr|trace)\s+(\d+)$/) { if (my $coro = find_coro $1) { trace $coro; } } elsif ($cmd =~ /^(?:ut|untrace)\s+(\d+)$/) { if (my $coro = find_coro $1) { untrace $coro; } } elsif ($cmd =~ /^cancel\s+(\d+)$/) { if (my $coro = find_coro $1) { $coro->cancel; } } elsif ($cmd =~ /^ready\s+(\d+)$/) { if (my $coro = find_coro $1) { $coro->ready; } } elsif ($cmd =~ /^kill\s+(\d+)(?:\s+(.*))?$/) { my $reason = defined $2 ? $2 : "killed"; if (my $coro = find_coro $1) { $coro->throw ($reason); } } elsif ($cmd =~ /^enable_times(\s+\S.*)?\s*$/) { my $enable = defined $1 ? 1*eval $1 : !Coro::State::enable_times; Coro::State::enable_times $enable; print "per-thread real and process time gathering ", $enable ? "enabled" : "disabled", ".\n"; } elsif ($cmd =~ /^help$/) { print < show a full backtrace of coroutine eval evaluate expression in context of trace enable tracing for this coroutine untrace disable tracing for this coroutine kill throws the given string in cancel cancels this coroutine ready force into the ready queue enable_times enable or disable time profiling in ps evaluate as perl and print results & same as above, but evaluate asynchronously you can use (find_coro ) in perl expressions to find the coro with the given pid, e.g. (find_coro 9768720)->ready EOF } elsif ($cmd =~ /^(.*)&$/) { my $cmd = $1; my $sub = eval "sub { $cmd }"; my $fh = select; Coro::async_pool { $Coro::current->{desc} = $cmd; my $t = Coro::Util::time; my @res = eval { &$sub }; $t = Coro::Util::time - $t; print {$fh} "\rcommand: $cmd\n", "execution time: $t\n", "result: ", $@ ? $@ : (join " ", @res) . "\n", "> "; }; } else { my @res = eval $cmd; print $@ ? $@ : (join " ", @res) . "\n"; } local $| = 1; } =item session $fh Run an interactive debugger session on the given filehandle. Each line entered is simply passed to C (with a few exceptions). =cut sub session($) { my ($fh) = @_; $fh = Coro::Handle::unblock $fh; my $old_fh = select $fh; my $guard = guard { select $old_fh }; my $loglevel = $SESLOGLEVEL; local $log{$Coro::current} = sub { return unless $_[0] <= $loglevel; print $fh "\015", (format_msg $_[0], $_[1]), "> "; }; print "coro debug session. use help for more info\n\n"; while ((print "> "), defined (my $cmd = $fh->readline ("\012"))) { if ($cmd =~ /^exit\s*$/) { print "bye.\n"; last; } elsif ($cmd =~ /^(?:ll|loglevel)\s*(\d+)?\s*/) { $loglevel = defined $1 ? $1 : -1; } elsif ($cmd =~ /^(?:w|watch)\s*([0-9.]*)\s+(.*)/) { my ($time, $cmd) = ($1*1 || 1, $2); my $cancel; Coro::async { $Coro::current->{desc} = "watch $cmd"; select $fh; until ($cancel) { command $cmd; Coro::Timer::sleep $time; } }; $fh->readable; $cancel = 1; } elsif ($cmd =~ /^help\s*/) { command $cmd; print < enable logging for messages of level and lower watch