#include <stdio.h>#include <stdlib.h>#include <pthread.h>voID *print_message_function(voID* parameter) { long *i = (long *)parameter; printf("Thread %ld\n",*i); pthread_exit(0);}int main(int argc,char *argv[]) { pthread_t threads[5]; long i = 0; for (i = 0; i < 5; i++) { pthread_create(&threads[i],print_message_function,(voID *)&i); } pthread_exit(NulL);}@H_404_2@但结果是:
Thread 2Thread 3Thread 3Thread 4Thread 5@H_404_2@要么:
Thread 0Thread 0Thread 0Thread 0Thread 0@H_404_2@当我再次运行它时它改变了.所以我不知道为什么我传递的值是(2到5)或全部(0)或…..(很多情况).我想我通过的论点是从0到4. @H_404_2@案例2: @H_404_2@当我更改为新代码时:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>voID *print_message_function(voID *parameter);int main(int argc,char *argv[]) { pthread_t threads[5]; int i = 0; for (i = 0; i < 5; i++) { char *msg = (char*)malloc(sizeof(char)); sprintf(msg,"Thread %d",i); pthread_create(&threads[i],(voID *)msg); }}voID *print_message_function(voID *parameter) { printf("%s\n",(char *)parameter);}@H_404_2@结果是:
Thread 1Thread 0Thread 3Thread 2Thread 4Thread 4@H_404_2@这意味着循环运行了6次!为什么?解决方法 将案例1更改为:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>voID *print_message_function(voID* parameter) { long i = (long)parameter; // <<< printf("Thread %ld\n",i); // <<< pthread_exit(0);}int main(int argc,(voID *)i); // <<< } pthread_exit(NulL);}@H_404_2@您之前看到不一致结果的原因是因为您向每个线程传递指针,其中每个指针指向同一个局部变量,然后您正在修改该局部变量. @H_404_2@在案例2中,您只对一个字符进行malLocing,然后尝试将字符串写入其中.它应该很容易修复. 总结
以上是内存溢出为你收集整理的linux – 参数在pthread中传递错误全部内容,希望文章能够帮你解决linux – 参数在pthread中传递错误所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)