我知道“printf”是标准c,应该是确定性的。但是当在 Qt 中运行时,我看到了一个更加不确定的响应(时钟周期)。这可能是由于 Qt 在其响应中添加了一些“猪肉”吗?
我有多个线程调用使用互斥锁的函数。当一个线程进入时,它会设置一个开关,以便其他线程在它完成之前不能。事情似乎正常工作了几秒钟,然后线程似乎从 10 到 1 个线程被杀死。所以我尝试添加延迟:(k=k+1:没有帮助),然后(循环 k=k+1:没有帮助),(usleep 有效),(printf)也可以创建随机延迟并允许所有线程继续运行。
void CCB::Write(int iThread)
{
static bool bUse = false;
bool bDone = false;
char cStr[20];
int posWrite;// = *m_posWrite; // issue of posWrite be altered with next extrance
long k = 0;
long m = 0;
m_threadCount++;
while(bDone == false){
if(bUse == false){
bUse = true;
posWrite = *m_posWrite;
memcpy(m_cmMessageCB + posWrite, &m_cmMessageWrite, sizeof(typeCanMessage));
memset(cStr, '\0', 20);
memcpy(cStr, (m_cmMessageCB + posWrite)->cMessage, 11); //fails: every 20
*m_posWrite = *m_posWrite + 1;
if(*m_posWrite == m_iNBufferLength)
*m_posWrite = 0;
bDone = true;
bUse = false;
}else if(bUse == true){
//why are threads being killed ?
// printf("T%d_%d ", iThread, m_threadCount);//non-deterministic value ?
usleep(1);//non-deterministic value
//k++;//delay of a couple clock cycles was not enough
/*
for(k = 0; k < iThread * 100; k++){//deterministic and fails to resolve thread problem
m++;
}
*/
}
}
}