+sub count_viewers {
+ my $unique = shift;
+ my $time = time;
+ my $share = IPC::ShareLite->new(
+ -key => 'RGLT',
+ -create => 'yes',
+ -destroy => 'no',
+ -size => 1048576,
+ ) or die "IPC::ShareLite: $!";
+ $share->lock(IPC::ShareLite::LOCK_EX);
+ my $viewers = {};
+ eval {
+ $viewers = Storable::thaw($share->fetch());
+ };
+ $viewers->{$unique} = time;
+
+ # Go through and remove old viewers, and count them at the same time.
+ my $num_viewers = 0;
+ while (my ($key, $value) = each %$viewers) {
+ if ($time - $value > 60) {
+ delete $viewers->{$key};
+ } else {
+ ++$num_viewers;
+ }
+ }
+
+ $share->store(Storable::freeze($viewers));
+ $share->unlock();
+
+ return $num_viewers;
+}
+