你能发现代码中的错误吗?门票最终低于0,导致长时间停车。简单的定制互斥失败
struct SContext {
volatile unsigned long* mutex;
volatile long* ticket;
volatile bool* done;
};
static unsigned int MyThreadFunc(SContext* ctxt) {
// -- keep going until we signal for thread to close
while(*ctxt->done == false) {
while(*ctxt->ticket) { // while we have tickets waiting
unsigned int lockedaquired = 0;
do {
if(*ctxt->mutex == 0) { // only try if someone doesn't have mutex locked
// -- if the compare and swap doesn't work then the function returns
// -- the value it expects
lockedaquired = InterlockedCompareExchange(ctxt->mutex, 1, 0);
}
} while(lockedaquired != 0); // loop while we didn't aquire lock
// -- enter critical section
// -- grab a ticket
if(*ctxt->ticket > 0);
(*ctxt->ticket)--;
// -- exit critical section
*ctxt->mutex = 0; // release lock
}
}
return 0;
}
调用函数等待线程完成
for(unsigned int loops = 0; loops < eLoopCount; ++loops) {
*ctxt.ticket = eNumThreads; // let the threads start!
// -- wait for threads to finish
while(*ctxt.ticket != 0)
;
}
done = true;
编辑:
的这个问题的答案很简单,后不幸的是我花的时间修剪下来的例子来发布简化版我在发布问题后立即找到答案。叹息..
我初始化lockaquired为0.然后作为优化不占用总线带宽,我不做CAS如果互斥体被采取。
不幸的是,在这种情况下,采取锁定while循环将让第二个线程通过!
对不起,额外的问题。我以为我不明白窗口低级同步原语,但我真的只是有一个简单的错误。
能否请您提供您的第二个代码示例的变量声明。 – Alerty 2011-04-28 06:40:45
@ereOn会做,感谢提醒! – coderdave 2011-04-28 06:53:05
@coderdave:Upvoted你的问题的良好行为:) – ereOn 2011-04-28 07:03:02