- #include <stdio.h>
#include <stdlib.h>
#include <thread.h>
/* compile with command line: cc myfile.c -lthread */
#define GetRandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
#define N ( (int)100)
#define PROTECTED 0 /* yes==1, no==0 */
#if PROTECTED
mutex_t cs;
#endif
int counter=0; /* shared variable */
bool wait=true;
/* simulate a two register CPU */
void CPU( void * delta)
{
register int reg1, reg2;
#if PROTECTED
mutex_lock( &cs); /* option to lock area */
#endif
reg1 = (int) delta; /* CPU register 1 <- copy delta */
reg2 = counter; /* CPU register 2 <- copy counter */
reg2 = reg2 + reg1; /* register-register addition */
-
sleep( GetRandom(0,10) ); /* simulate random interrupts of CPU */
- counter = reg2; /* copy register to RAM */
#if PROTECTED
mutex_unlock( &cs); /* option to unlock area */
#endif
printf("count is %d\n", counter);
}
void CheckKey( void *dummy ) /* daemon process to look for a pressed */
{ /* key, any key. */
_getch();
wait = false;
}
void main() {
int i, sum = (N*(N-1))/2;
#if PROTECTED
mutex_init( &cs); /* setup binary semaphore */
#endif
/* start background thread */
thr_create(NULL, NULL, CheckKey, 0, THR_DAEMON | THR_LWP_CREATE, NULL);
- /* give each CPU its marching orders */
for(i=0; i<N; i++)
thr_create(NULL,NULL, CPU, (void *) i, THR_LWP_CREATE, NULL);
while (wait ) /* check if daemon has found a pressed key */
sleep(100L); /* take a nap between ... */
printf("total should be %d, and is computed as %d\n", sum, counter);
}
|