NAME
Coro::Channel - message queues
SYNOPSIS
use Coro;
$q1 = new Coro::Channel <maxsize>;
$q1->put ("xxx");
print $q1->get;
die unless $q1->size;
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 Coro::Channel manually, it will be loaded automatically when you use Coro and call the new constructor.
- $q = new Coro:Channel $maxsize
-
Create a new channel with the given maximum size (practically unlimited if
maxsizeis 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, andputwill wait until there is a correspondinggetcall). To buffer one element you have to specify2, and so on. - $q->put ($scalar)
-
Put the given scalar into the queue.
- $q->get
-
Return the next element from the queue, waiting if necessary.
- $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
undef, almost as if infinitely manyundefelements had been put into the queue.Specifically, this function wakes up any pending
getcalls and lets them returnundef, the same on futuregetcalls.sizewill return the real number of stored elements, though.Another way to describe the behaviour is that
getcalls will not block when the queue becomes empty but immediately returnundef. This means that calls toputwill work normally and the data will be returned on subsequentgetcalls.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
putdata into the Channel and one or more consumers whogetthem. When all producers have finished producing data, a call toshutdownsignals this fact to any consumers.A common implementation uses one or more threads that
getfrom a channel until it returnsundef. To clean everything up, firstshutdownthe channel, thenjointhe threads. - $q->size
-
Return the number of elements waiting to be consumed. Please note that:
if ($q->size) { my $data = $q->get; ... }is not a race condition but instead works just fine. Note that the number of elements that wait can be larger than
$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 precisely the number of calls to
getthat will succeed instantly and return some data. Callingshutdownhas no effect on this number.
AUTHOR/SUPPORT/CONTACT
Marc A. Lehmann <schmorp@schmorp.de>
http://software.schmorp.de/pkg/Coro.html