#define SORT_LIST 128 #include #include void *compare_exchange(); int sort_array[SORT_LIST]; int j; main() { clock_t t1, t2; pthread_attr_t attr; pthread_t *p_threads; int i, ii; /* we need half as many threads as number of elements */ p_threads = (pthread_t *) malloc((SORT_LIST/2) * sizeof(pthread_t)); pthread_attr_init (&attr); pthread_attr_setscope (&attr,PTHREAD_SCOPE_SYSTEM); /* set up array here */ for (i=0; i< SORT_LIST; i++) sort_array[i] = rand() % 1000; t1 = clock(); for (ii = 0; ii < SORT_LIST; ii++) { for (i=0; i< SORT_LIST / 2 - ii % 2; i++) { j = 2 * i + (ii % 2); pthread_create(&p_threads[i], &attr, compare_exchange, (void *)&sort_array[j]); } for (i=0; i< SORT_LIST / 2 - ii % 2; i++) { pthread_join(p_threads[i], NULL); } } t2 = clock(); printf("CPU time (not wall clock time) %f\n", (float)t2/1000000); for (i=0; i< SORT_LIST; i++) printf("%d ", sort_array[i]); printf("\n"); } void *compare_exchange(int *s) { int temp; if (s[0] > s[1]) { temp = s[0]; s[0] = s[1]; s[1] = temp; } pthread_exit(0); }