/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include /* * unorderly_threads.c -- demonstrates potential problems with unsynchronized manipulation of shared variables */ #define MAXTH 20 #define MAX 50000 int arr[MAX+MAXTH]; int idx; // global index to array void *fill_array(void *tid) { while ( idx < MAX ) { arr[idx] = idx; idx++; } pthread_exit(NULL); } int main(int argc, char *argv[]) { int rc; int i; pthread_t threads[MAXTH]; for( i = 0; i < MAXTH; i++) { rc = pthread_create(&threads[i], NULL, fill_array, (void *)i); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } for ( i = 0; i < MAXTH; i++ ) { rc = pthread_join(threads[i], NULL); } // print all entries that have been messed up by unoderly modification and access by threads for ( i = 0; i < MAX; i++ ) { if ( arr[i] != i ) { fprintf(stderr, "arr[%d]: %d\n", i, arr[i]); } } pthread_exit(NULL); }