【发布时间】:2016-09-30 19:44:17
【问题描述】:
我对 C 中的线程相当陌生。对于这个程序,我需要声明一个线程,我在 for 循环中传递该线程,以便从线程中打印出 printfs。
我似乎无法让它以正确的顺序打印。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 16
void *thread(void *thread_id) {
int id = *((int *) thread_id);
printf("Hello from thread %d\n", id);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
int code = pthread_create(&threads[i], NULL, thread, &i);
if (code != 0) {
fprintf(stderr, "pthread_create failed!\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//gcc -o main main.c -lpthread
【问题讨论】:
-
这是一个错误的期望。线程启动/执行顺序不需要与创建顺序相同。
-
这是一个很好的
pthread教程:computing.llnl.gov/tutorials/pthreads