【发布时间】:2018-08-17 12:03:38
【问题描述】:
在以下代码中,threadCount 是 1,2,3,4 之一。但是在输出中,虽然字符串部分得到完美打印,但 num 值会随机丢失,并且有时会在几行之后附加。
void *SPWork(void *t)
{
int* threadC = (int*)t;
int threadCount = *threadC;
cout<<"\n Thread count" << threadCount << endl;
cout << flush;
long long int i, adjustedIterationCount;
adjustedIterationCount = 100/(threadCount);
for (i=0; i< adjustedIterationCount; i++)
{
i++ ;
}
pthread_exit((void*) t);
}
输出
......
.....
Thread count1
Thread count1
Thread count2
Thread count1
Thread count
Thread count
Thread count234
.....
.....
注意最后一行线程的值是 234。但该值永远不会是 234。在前 2 行中,该值没有被附加,因此 2,3 被添加到这一行。
我知道这与刷新或附加“\n”有关,尝试了很多组合。但是,问题仍然存在。
注意这是一个 pthread 的工作方法,编译器标志是"-g -Wall -O3 -lpthread"
【问题讨论】:
-
当您有许多线程都写入同一个 IO 设备时,您无法预测。东西要么需要用互斥锁保护,要么你必须学会忍受所有线程相互切断。
-
这不是线程安全的。您正在为所有线程使用
t。并且从未使用过i。 -
@codekaizer,不一定,每个线程都可以得到自己的自己的
t。没有看到线程创建代码,我们不知道。在任何情况下,函数中都没有实际更改t. -
“我从未使用过。”是的,一些代码被剥离以使其清晰......
-
Near duplicate(至少我的回答涵盖了这个问题)。