【发布时间】:2010-08-26 06:52:14
【问题描述】:
我正在尝试通过在必要时跳过昂贵的事件操作来提高生产者/消费者线程情况的效率,例如:
//cas(variable, compare, set) is atomic compare and swap
//queue is already lock free
running = false
// dd item to queue – producer thread(s)
if(cas(running, false, true))
{
// We effectively obtained a lock on signalling the event
add_to_queue()
signal_event()
}
else
{
// Most of the time if things are busy we should not be signalling the event
add_to_queue()
if(cas(running, false, true))
signal_event()
}
...
// Process queue, single consumer thread
reset_event()
while(1)
{
wait_for_auto_reset_event() // Preferably IOCP
for(int i = 0; i < SpinCount; ++i)
process_queue()
cas(running, true, false)
if(queue_not_empty())
if(cas(running, false, true))
signal_event()
}
显然试图让这些事情变得正确有点棘手(!)那么上面的伪代码是否正确?一个比实际需要的更多的事件信号的解决方案是可以的,但不是一个对每个项目都这样做的解决方案。
【问题讨论】:
-
你的代码是什么语言的?
-
是事件操作昂贵还是消费者线程处理也昂贵? (你也想避免这种情况?)
-
对不起,我现在才注意到所有这些反馈!尽管我对在 CSharp 中复制类似内容感兴趣,但它在 C++ 中。如果对队列中的每个项目都进行事件同步操作,则该操作是最昂贵的。
标签: multithreading thread-safety producer-consumer