我正在练习一些多线程程序,但我无法弄清楚这个输出背后的逻辑。
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
int print_message(void* ptr);
int main()
{
pthread_t thread1,thread2;
char *mesg1 = "Thread 1";
char *mesg2 = "Thread 2";
int iret1, iret2;
pthread_create(&thread1, NULL, print_message, (void *)mesg1);
pthread_create(&thread2, NULL, print_message, (void *)mesg2);
pthread_join(thread1,(void*)&iret1 );
pthread_join(thread2, (void*)&iret2);
printf("Thread 1 return : %d\n", (int)iret1);
printf("Thread 2 return : %d\n", (int)iret2);
return 0;
}
int print_message(void *ptr)
{
char *mesg;
static int i=0;
mesg = (char *)ptr;
printf("%s\n",mesg);
i++;
return ((void*)i);
}
Run Code Online (Sandbox Code Playgroud)
我期待输出
Thread 1
Thread 2
Thread 1 return : 1
Thread 2 return : 2
Run Code Online (Sandbox Code Playgroud)
但我得到了输出
Thread 1
Thread 2
Thread 1 return : 0
Thread 2 return : 2
Run Code Online (Sandbox Code Playgroud)
有人可以向我澄清一下吗?如果 pthread 函数的使用有任何错误,请指出。
该变量i在两个线程之间共享,因为它是static. 在多个线程之间修改变量的行为是未定义的,因此,事实上,无论是你得到的输出还是你想要得到的输出都是 \xe2\x80\x9cwrong\xe2\x80\x9d 从编译器处于下的意义上来说没有义务将其提供给您。事实上,我能够根据我使用的优化级别来改变输出,并且它无疑会根据平台而有所不同。
如果你想修改i,你应该使用互斥体:
int print_message(void *ptr)\n{\n static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\n char *mesg;\n static int i=0;\n int local_i;\n\n mesg = (char *)ptr;\n printf("%s\\n",mesg);\n if (pthread_mutex_lock(&mutex) == 0) {\n local_i = ++i;\n pthread_mutex_unlock(&mutex);\n }\n return ((void*)local_i);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n如果不使用互斥体,您将永远无法确保获得您认为应该获得的输出。
\n