NAME

MCE::Shared::Condvar - Class providing condition variables for MCE::Shared

VERSION

This document describes MCE::Shared::Condvar version 1.699_003

SYNOPSIS

use MCE::Shared;

my $cv = MCE::Shared->condvar( 0 );

# oo interface
$cv->lock();
$cv->unlock();
$cv->broadcast();
$cv->broadcast(0.05);        # yield some time before broadcast
$cv->signal();
$cv->signal(0.05);           # yield some time before signal
$cv->timedwait(2.5);
$cv->wait();

$val = $cv->set( $val );
$val = $cv->get();
$len = $cv->length();

# sugar methods without having to call set/get explicitly
$val = $cv->append( $string );             #   $val .= $string
$val = $cv->decr();                        # --$val
$val = $cv->decrby( $number );             #   $val -= $number
$val = $cv->incr();                        # ++$val
$val = $cv->incrby( $number );             #   $val += $number
$val = $cv->pdecr();                       #   $val--
$val = $cv->pincr();                       #   $val++

DESCRIPTION

Helper class for MCE::Shared.

The following demonstrates barrier synchronization.

use MCE;
use MCE::Shared;
use Time::HiRes qw(usleep);

my $num_workers = 8;
my $count = MCE::Shared->condvar(0);
my $state = MCE::Shared->scalar('ready');

# Sleeping with small values is expensive on Cygwin (imo).
my $microsecs = ($^O eq 'cygwin') ? 0 : 200;

# Lock is released when calling ->broadcast, ->signal, ->timedwait,
# or ->wait. Thus, re-obtain the lock for synchronization afterwards
# if desired.

sub barrier_sync {
   usleep($microsecs) until $state->get eq 'ready' or $state->get eq 'up';

   $count->lock;
   $state->set('up'), $count->incr;

   if ($count->get == $num_workers) {
      $count->decr, $state->set('down');
      $count->broadcast;
   }
   else {
      $count->wait while $state->get eq 'up';
      $count->lock;
      $count->decr;
      $state->set('ready') if $count->get == 0;
      $count->unlock;
   }
}

# Time taken from a 2.6 GHz machine running Mac OS X.
# If you want a fast barrier synchronization, let me know.
# I can add MCE::Shared::Barrier to behave like MCE Sync.
#
#    threads::shared:   0.238s  threads
#      forks::shared:  36.426s  child processes
#        MCE::Shared:   0.397s  child processes
#           MCE Sync:   0.062s  child processes

sub user_func {
   my $id = MCE->wid;
   for (1 .. 400) {
      MCE->print("$_: $id\n");
      ## MCE->sync();  # via MCE Core API
      barrier_sync();  # via MCE::Shared::Condvar
   }
}

my $mce = MCE->new(
   max_workers => $num_workers,
   user_func   => \&user_func
)->run;

API DOCUMENTATION

To be completed before the final 1.700 release.

new
lock
unlock
broadcast
signal
timedwait
wait
set
get
length
append
decr
decrby
incr
incrby
pdecr
pincr

INDEX

MCE, MCE::Core, MCE::Shared

AUTHOR

Mario E. Roy, <marioeroy AT gmail DOT com>