AnyEvent equivalent to Event var watcher?
I'm using an Event
var watcher to implement an internal queue. When the producer thread adds something to the queue (just an array) it will change the value of a w开发者_开发问答atched variable to signal that an element was added.
How can you do the same with AnyEvent
? It doesn't seem to support variable watching. Do I have to use pipes and use an IO watcher (i.e. the producer writes a byte on one end of the pipe when it has added an element.)
I'd also be interested to know how to do this with Coro
.
It sounds as if you are using variable watching as means of transferring control back to the consumer. In AnyEvent, this can be done with condition variables by calling $cv->send() from the producer and $cv->recv() in the consumer. You could consider send()ing the item that you'd otherwise have put in the queue, but calling send without parameters should be an allowed way of notifying the consumer.
I figured out the paradigm to use:
my @queue;
my $queue_watcher;
sub add_item {
push(@queue, $_[0]);
$queue_watcher ||= AnyEvent->timer(after => 0, cb => \&process_queue);
}
sub process_queue {
... # remove zero or more elements from @queue
if (@queue) {
$queue_watcher = AnyEvent->timer(after => 0, cb => \&process_queue);
} else {
undef $queue_watcher;
}
}
Basically $queue_watcher
is defined and active if and only if @queue
is not empty.
精彩评论