/* A Round Robin Program in PVM.  This program will start on one
computer, and then pass control to a second which in turn will
pass control to a third, and so on until some maximum number is
is reached.  Then control is sent back to the original process.
*/

#include <stdio.h>
#include "/usr/pvm3/include/pvm3.h"
#define SLAVENAME "relay1"
#define MAX 10		// Maximum processes
main()
{
    int nproc;		// Number of processes
    int i;		// Loop variable

    int numtasks,	// Number of tasks
        who, 		// Who sent process
        msgtype, 	// Message Type
        count;		// Counter for Nth pass 

    int mytid;     	// My Task ID 
    int tids[MAX];	// Array of Slave Tasks 

    struct pvmhostinfo *hostp[MAX]; // Environment 

    printf("Round Robin Program\n");
    printf("Enter number of processes:");
    scanf ("%d", &nproc);
    if ((nproc < 1) || (nproc > 10))
           nproc = MAX;  // Check for input error 

// Enroll in pvm 
    mytid = pvm_mytid(); // Get my task ID

// Start up slave tasks 
    numtasks = pvm_spawn(SLAVENAME, (char**)0, 0, "", nproc, tids);

// List all current data for Task Array
    for (i=0; i < nproc; i++) {
      printf("Task[ %d ]: %d\n", i, tids[i]);
    }
   who = mytid;  // Establish me as Originator
 
// Broadcast data to first slave task 

    count = 0;  	// set count to zero
    msgtype = 99;	// message type when passing 
    printf("Sending data: %d  %d \n", count, who);

    pvm_initsend(PvmDataDefault);  // Init buffer
    pvm_pkint(&count, 1, 1);    // Current count 
    pvm_pkint(&nproc, 1, 1);    // Number of processes 
    pvm_pkint(&who, 1, 1);	// Original master
    pvm_pkint(tids, nproc, 1);	// Array of Task IDs
    pvm_send(tids[count], msgtype); // Send message 

// Wait for results from slaves 
    msgtype = 666;  	// message type when done 
    printf("Waiting to receive\n");

    pvm_recv( -1, msgtype );	// Wait for message
    pvm_upkint( &count, 1, 1 );	// Get final count 
    pvm_upkint(&who, 1, 1);	// Who sent message 

// Display results
    printf("Count:  %d  Last:  %d\n", count, who);  
   

// Program Finished - exit PVM before stopping 
    pvm_exit();
}

