void *incrementCounter(void *thr_id) { int tid = (int)thr_id; printf("thread %d started incrementing ID - %lu\n", tid, thrd_current());
for (int i = 0; i < MAX_ITER; ++i) counter += 1;
return (void *)counter; }
intmain(int argc, charconst *argv[]) { thrd_t threads[NUM_THREADS]; int rc, sum = 0;
for (int i = 0; i < NUM_THREADS; ++i) { rc = thrd_create(&threads[i], (thrd_start_t)incrementCounter, (void *)i); if (rc == thrd_error) { printf("ERORR; thrd_create() call failed\n"); exit(EXIT_FAILURE); } }
int retval; for (int i = 0; i < NUM_THREADS; ++i) { thrd_join(threads[i], &retval); sum += retval; } printf("count = %d\n", sum);
thrd_exit(EXIT_SUCCESS); }
输出:
1 2 3 4 5
thread 0 started incrementing ID - 281473108406528 thread 3 started incrementing ID - 281472963440896 thread 1 started incrementing ID - 281473099952384 thread 2 started incrementing ID - 281473091498240 count = 40000
若不加的输出(各个线程在竞争数据):
1 2 3 4 5
thread 0 started incrementing ID - 281473865281824 thread 2 started incrementing ID - 281473848373536 thread 1 started incrementing ID - 281473856827680 thread 3 started incrementing ID - 281473768747296 count = 55938