更新时间:2022-06-27 02:41:08
您必须等待使用pthread_join
完成主线程中的所有线程,然后才能看到所有线程都显示一些值
You have to wait for all the threads to complete in the main using pthread_join
, only then u can see all of them display some value
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 10
void *thread_func(void *arg)
{
int v = (int)arg;
printf("v = %d\n", v);
return (void*)0;
}
int main(int argc, const char *argv[])
{
pthread_t pids[THREAD_NUM];
int rv;
int i;
for (i = 0; i < THREAD_NUM; i++) {
rv = pthread_create(&pids[i], NULL, thread_func, (void*)i);
if (rv != 0) {
perror("failed to create child thread");
return 1;
}
}
for (i = 0; i < THREAD_NUM; i++) {
pthread_join(pids[i], NULL);
}
return 0;
}
示例运行输出:
[root@fc ~]# ./a.out
v = 0
v = 2
v = 4
v = 6
v = 7
v = 8
v = 9
v = 5
v = 3
v = 1