使用条件变量(POSIX 并发 api)真的会减慢我的并行网络代码吗?
我目前正在编写一个应用程序来管理多台计算机上的并行渲染。为此,我在我的服务器应用程序上有一个管理 TCP 连接的线程池,每个问题都有一个线程。我想在每个 TCP 线程中使用相同的条件变量来警告其他线程(如果网络线程之一收到数据)。
问题:要在 POSIX api 中使用 signal
函数,我必须使用互斥体。这意味着如果 2 个网络线程同时接收数据,它们将必须等待互斥体空闲才能继续执行。
实际上,使用这个条件变量真的会减慢我的代码速度吗?如果我不想使用它,我也可以在另一个线程(对条件变量调用 wait
的线程)中创建一条 while 指令,循环查看我的网络线程是否收到了某些内容。
多谢 :)
I'm currently programming an application that manages parallel rendering on several computers. For that, I have on my server application a pool of threads that manages the TCP connections, one thread for every question. I'd like to use the same condition variable in every TCP thread to warn an other thread if one of the network threads received data.
Problem : to use the signal
function in the POSIX api, I have to use a mutex. That means that if 2 network threads receive data at the same time, they will have to wait for the mutex to become free to continue execution.
Realistically, will the use of this condition variable really slow down my code? I also can, if I don't want to use it, make in the other thread (the one who calls wait
on the condition variable) a while instruction that loops to see if my network threads received something.
Thanks a lot :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能不会。如果您所做的只是锁定互斥锁并发出条件变量信号,那么它并不比获取受互斥锁保护的工作队列中的下一项更糟糕。
理论上,您可以用轮询标志的 while 循环替换对条件变量的等待,但随后您必须确保在访问该标志时使用正确的同步(内存屏障)。这也是有代价的。由于各种原因,繁忙的等待也并不理想,并且添加睡眠会引入延迟。
Probably not. If all you do is locking the mutex and signaling the condition variable it is no worse than getting the next item in a mutex-protected work queue.
You could theoretically replace your wait on the condition variable with a while loop polling a flag, but then you must make sure to use proper synchronization (memory barriers) when accessing this flag. This will also come at a cost. A busy wait is also not ideal for various reasons, and adding a sleep will introduce delay.