/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1987, 1991 by John E. Lloyd.			    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

/* Program to test mutual exclusion using memory objects (pieces of
   memory allocated with allocMem() ) */

#include "../h/rci.h"

#include "mxtest.h"

extern mutexTest();

main(argc, argv)
int argc;
char **argv;
{
	RCI_DESC *td;
	int *obj;
	int doMutex = 1;
	int setBuf[MEMSIZE];
	int getBuf[MEMSIZE];
	int k;
	int numTries = 0;
	int numCollisions = 0;

	argc--; argv++;
	while (argc)
	 { if (ARGUMENT ("-off"))
	    { doMutex = 0;
	    }
	   else
	    { argc = -1;
	      break;
	    }
	   argc--; argv++;
	 }
	if (argc == -1)
	 { usageMsg (-1, "mxtest [-off]\n");
	 }
	rciSetOptions (EXIT_ON_ERROR);

	for (k=0; k<MEMSIZE; k++)
	 { setBuf[k] = 1;
	 }

	obj = (int*)allocMem ("obj", MEMSIZE*sizeof(int), 0);
	td = rciCreate ("test", 0x2);
	rciScheduling (td, ON_CLOCK, 0);
	rciRate (td, 100, 0);
	rciControlFxns (td, NULLF, mutexTest, NULLF, doMutex);

	rciStart (~0);
	while (1)
	 { int val0;
	   if (!doMutex)
	    { bcopy (obj, getBuf, MEMSIZE*sizeof(int));
	      bcopy (setBuf, obj, MEMSIZE*sizeof(int));
	    }
	   else
	    { readMem (obj, getBuf);
	      writeMem (obj, setBuf);
	    }
	   val0 = getBuf[0];
	   for (k=1; k<MEMSIZE; k++)
	    { if (getBuf[k] != val0)
	       { numCollisions++;
		 break;
	       }
	    }
	   numTries++;
	   if ((numTries % 10000) == 0)
	    { printf ("%8d tries, %d collisions\n",
			numTries, numCollisions);
	    }
	 }
}
