- 论坛徽章:
- 0
|
5可用积分
高手们看看这个多线程问题怎么用不正确的方式传递了参数,请详细讲讲哦,小弟感激不尽
- #include<pthread.h>
- #include<stdio.h>
- #include<string.h>
-
- #define NUM 10
-
- static void *
- printarg(void *arg){
- fprintf(stderr, "Thread reveived %d\n", *(int *)arg);
- return NULL;
- }
-
- int
- main(void)
- {
- int error, i , j;
- pthread_t tid[NUM];
-
- for(i = 0;i < NUM; i++)
- if(error = pthread_create(tid + i; NULL, printarg, (void *)&i))
- fprintf(stderr, "Failed to create thread\n");
- for(j = 0;j < NUM; j++){
- if(pthread_equal(pthread_self(), tid[j]))
- continue;
- if(error = pthread_join(tid[j], NULL))
- fprintf(stderr, " Failed to join thread\n");
- }
- printf("All the threads done\n");
- return 0;
- }
复制代码 |
最佳答案
查看完整内容
你传递的是i的地址,相当于多个线程共用一个变量i。你直接传递数值就没有问题。创建线程:pthread_create(tid + i; NULL, printarg, (void *)i))线程中打印:fprintf(stderr, "Thread reveived %d\n", (int)arg);
|