#!/usr/bin/perl   

# example PerlDSM application; finds the average load average among all
# nodes

use DSMClnt;

package main;

# shared variables:
$SumAvgs;  # sum of all load averages

# global non-shared variables:
$NumNodes;  # total number of application nodes
$MyNode;  # number of this node
$SvrSkt;  # server socket ID for this node

# check in with server
($SvrSkt,$NumNodes,$MyNode) = DSMClnt::DSMCheckIn();
print "total of ", $NumNodes, " nodes, of which I am number ",$MyNode, "\n";

# tie shared variables
# arguments (the variable name is given first but is not considered an
# argument to tie()):  variable name; 'DSMClnt'; variable type (0 for
# scalar, 1 for array, 2 for hash); single-quoted variable name (if
# array or hash, then base name with $ sign only); subscript (-1 if
# scalar); server socket
tie $SumAvgs,'DSMClnt',0,'$SumAvgs',-1;
tie $LOCK,'DSMClnt',0,'$LOCK',-1;
tie $BARR,'DSMClnt',0,'$BARR',-1;

# initialize sum to 0 if I am node 0
if ($MyNode == 0)  {
   $SumAvgs = 0.0;
}

# barrier
$Dummy = $BARR;  # left-hand side irrelevant

# get load average at this node
system 'w > tmpout';
open TMP,"tmpout";
$Line = <TMP>;
@Tokens = split(" ",$Line);
$MyAvg = $Tokens[8];

# add to system total; critical section
$Dummy = $LOCK;  # left-hand side irrelevant
$SumAvgs = $SumAvgs + $MyAvg;
$LOCK = 0;    # right-hand side irrelevant
# end of critical section

# wait for everyone to finish, then write answer if I am node 0
$Dummy = $BARR;
if ($MyNode == 0)  {
   print $SumAvgs/$NumNodes, "\n";
}

$Dummy = $BARR;
DSMClnt::DSMExit();


