#!/usr/bin/perl   

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

use DSMScalar;
use DSMUtils;

package main;

# globals:
$SvrSkt;  # socket to server
$NumNodes;  # total number of (non-server) nodes
$MyNode;  # number of this node

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

# tie shared variables
tie $BARR,'DSMScalar','$BARR',$SvrSkt;
tie $SumAvgs,'DSMScalar','$SumAvgs',$SvrSkt;
tie $LOCK,'DSMScalar','$LOCK',$SvrSkt;

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

# barrier
$Barr = $BARR;


# get my load average, and add to system total

system 'w > tmpout';
open TMP,"tmpout";
$Line = <TMP>;
@Tokens = split(" ",$Line);
$MyAvg = $Tokens[9];
$Lock = $LOCK;
$SumAvgs = $SumAvgs + $MyAvg;
$LOCK = 0;  

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

DSMUtils::DSMCloseSocket($SvrSkt);
close $SvrSkt;

exit;

