这是我的场景。首先,我有一个结构——
struct interval
{
double lower;
double higher;
}
现在我的线程函数 -
void* thread_function(void* i)
{
interval* in = (interval*)i;
double a = in->lower;
cout << a;
pthread_exit(NULL)
}
在 main 中,假设我创建了这 2 个线程 -
pthread_t one,two;
interval i;
i.lower = 0; i.higher = 5;
pthread_create(&one,NULL,thread_function,&i);
i.lower=10; i.higher = 20;
pthread_create(&two,NULL,thread_function, &i);
pthread_join(one,NULL);
pthread_join(two,NULL);
问题来了。理想情况下,线程“一”应该打印出 0,线程“二”应该打印出 10。然而,这并没有发生。有时,我最终会得到两个 10。
这是设计使然吗?换句话说,在创建线程时,i.lower 中的值已经在 main 中更改,因此两个线程最终使用相同的值?
最佳答案
Is this by design?
是的。线程何时开始以及它们何时访问该值是未指定的。您需要给他们每个人自己的数据拷贝。
关于c++ - pthreads - 先前创建的线程使用新值(线程创建后更新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758561/