我编写了一个代码来打印出字符串:使用pthread将“Thread 0”改为“Thread 4”.
这是我的代码:
情况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,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); }
但结果是:
Thread 2 Thread 3 Thread 3 Thread 4 Thread 5
要么:
Thread 0 Thread 0 Thread 0 Thread 0 Thread 0
当我再次运行它时它改变了.所以我不知道为什么我传递的值是(2到5)或全部(0)或…..(很多情况).我想我通过的论点是从0到4.
案例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); }
结果是:
Thread 1 Thread 0 Thread 3 Thread 2 Thread 4 Thread 4
这意味着循环运行了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); }
您之前看到不一致结果的原因是因为您向每个线程传递指针,其中每个指针指向同一个局部变量,然后您正在修改该局部变量.
在案例2中,您只对一个字符进行mallocing,然后尝试将字符串写入其中.它应该很容易修复.