【发布时间】:2016-01-29 12:32:26
【问题描述】:
我在多线程中遇到问题。请考虑以下代码:
#include<stdio.h>
#include<pthread.h>
void* functionA(void*);
void* functionB(void*);
int main()
{
pthread_t tid[2];
pthread_attr_t arg;
for(int i = 0; i<2; ++i)
{
pthread_attr_init(&arg);
if(i == 0)
{
int x = 0;
pthread_create(&tid[i], &arg, functionA, (void*)&x);
}
else if(i == 1)
{
int x = 6;
pthread_create(&tid[i], &arg, functionB, (void*)&x);
}
}
// wait for both threads to finish execution...
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
//.........................DEFINATIONS........................
void* functionA(void* x)
{
int Index = *((int*)x);
printf("First: %d\n",Index); //..................... LINE M
}
void* functionB(void* x)
{
int Index = *((int*)x);
printf("Second: %d\n",Index); //....................... LINE N
}
现在我相信 functionA 将首先开始执行,因为当然 functionA 的线程将首先在 for 循环中创建,所以根据我的输出应该是:
First: 0 (from Line M)
Second: 6 (from Line N)
但实际输出是,
Second: 6
First: 6
现在看到这个我真的很惊讶,我不知道发生了什么。不仅 secondFunction 首先开始执行,而且两个函数都显示相同的值,即 6,这对我来说没有意义。谁能解释一下这里发生了什么???? 在此先感谢...
【问题讨论】:
-
x在您创建线程后立即超出范围,因此您的代码显示 UB。 -
尝试在您的线程中执行此操作:
printf("%p\n", x);,我猜,您会看到,两个线程的指针是相同的,因为您的int x = 0/6;在本地范围内,因此它们可能会结束向上分配在同一地址。 -
所以您正在使用线程,但您希望它们之间有特定的执行顺序?你认为启动线程和调用方法的区别是什么?
-
@Roman Hocke:是的,我明白你的意思了,谢谢 :)
标签: c multithreading pthreads