#include #include #include #include #include static int num_ops; static pthread_t *thr_array; static void * thr_main(void *arg) { int i; int sum = 0; for (i = 0; i < num_ops; i++) { sum += i; } return (void *)(intptr_t)sum; } static void spawn_thread(int thr) { int ret; ret = pthread_create(&thr_array[thr], NULL, thr_main, NULL); if (ret != 0) { fprintf(stderr, "pthread_create: %s\n", strerror(ret)); exit(1); } } static void join_thread(int thr) { int ret; ret = pthread_join(thr_array[thr], NULL); if (ret != 0) { fprintf(stderr, "pthread_join: %s\n", strerror(ret)); exit(1); } } int main(int argc, char *argv[]) { int num_spawns; int num_threads; int thr; int thr_saved; int ret; int spawn_count; if (argc != 4) { fprintf(stderr, "Usage: oprofile_multithread_test \n"); exit(1); } num_spawns = atoi(argv[1]); num_threads = atoi(argv[2]); num_ops = atoi(argv[3]); if (num_threads < 1) { fprintf(stderr, "Number of threads must be positive.\n"); exit(1); } thr_array = malloc(sizeof(pthread_t) * num_threads); if (thr_array == NULL) { fprintf(stderr, "Cannot allocate thr_array\n"); exit(1); } spawn_count = 0; for (thr = 0; thr < num_threads; thr++) { spawn_thread(thr); spawn_count++; } thr = 0; while (num_spawns < 0 ? 1 /* infinite loop */ : spawn_count < num_spawns) { join_thread(thr); spawn_thread(thr); thr = (thr + 1) % num_threads; spawn_count++; } thr_saved = thr; do { join_thread(thr); thr = (thr + 1) % num_threads; } while (thr != thr_saved); free(thr_array); }