/* pthreadex.c */ /* This version is used to test Peterson's algorithm for N threads */ /* To compile (on a Solaris == SunOS 5.x machine ) */ /* cc pthreadex.c -lpthread -lrt */ /* To run */ /* a.out 1000000 */ #include #include #include #define MAX_THREADS 16 /* Maximum possible number of threads */ #define NUM_THREADS 2 /* Number of threads to us in this run */ pthread_t td[MAX_THREADS]; /* Thread descriptors for the new threads */ pthread_attr_t attr; pthread_mutex_t t_mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t t_cond = PTHREAD_COND_INITIALIZER; volatile int shared = 0; /* The shared variable being updated */ int loopcount = 100000; /* Default value for increment count */ int lastid = 0; void pete_lock(int tid); void pete_unlock(int tid); /* We will run instances of this function as separate threads */ void xthread( int id) /* Logical thread id.. values are 0, 1, 2,... */ { int i; int local; /* sleep(1); */ printf("Made it in %d \n", id); for (i = 0; i < loopcount; i++) { pete_lock(id); local = shared; local += 1; shared = local; pete_unlock(id); } pthread_exit((void *)0); } int main( int argc, char **argv) { int tid; int pri; int stat; int tstatus; /* Override loop count if user supplied one */ if (argc > 1) sscanf(argv[1], "%d", &loopcount); pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); /* Create the threads */ for (tid = 0; tid < NUM_THREADS; tid++) { pthread_create(&td[tid], &attr, (void *)xthread, (void *)tid); } /* Wait for all to terminate */ for (tid = 0; tid < NUM_THREADS; tid++) { stat = pthread_join(td[tid], NULL); printf("Thread %d done \n", tid); } printf("Made it out \n"); printf("Value of shared is %d \n", shared); return(0); }