#!/usr/bin/perl
package Counter;
use strict;
use Coro::Continuation;
our $id_gen = 0;
sub new {
my $class = shift;
my $self = { @_ };
bless $self, $class;
$self->{count} = 0;
$self->{id} = $id_gen++;
$self->{continuation} = continuation { $self->main };
return $self;
}
sub process {
my ($self, $request) = @_;
$self->{continuation}->();
}
sub main {
my $self = shift;
while(1) {
my $action = $self->{request}->param("action-$self->{id}");
if($action eq 'add') {
$self->{count}++;
} elsif($action eq 'sub') {
$self->{count}--;
}
$self->{output} = qq{
Count: $self->{count}
++
--
};
yield;
}
}
package main;
use strict;
use Continuity;
Continuity->new( port => 8080 )->loop;
sub main {
my ($request) = @_;
my $output;
my @counters;
for my $i (1..10) {
my $counter = Counter->new( request => $request );
push @counters, $counter;
}
while(1) {
foreach my $counter (@counters) {
$counter->process();
$request->print($counter->{output});
}
$request->next;
}
}