在 C 中执行跨平台线程间通知的好方法是什么?
设想: - 我的主(UI)线程(线程“M”)运行,并启动工作线程(“W”)来控制某些硬件。 - “W”想要经常向“M”发送进度通知。 - 通知调用不能阻塞“W”...“W”需要调用并立即返回; “M”将异步处理通知,并且不会向“W”返回任何内容。 - “M”必须通过线程“M”上运行的回调来通知。 - 必须能够传递数据(不用担心数据的线程安全性)。
.NET 在其 System.ComponentModel.AsyncOperation 类中就有这样的工具,但我想要创建跨平台代码,而不仅仅是 .NET 甚至严格的 Win32(尽管我的第一个平台是 Win32 上的本机 c++)。
使用 Boost 将是一个优势。
我读过这个: Boost:触发并忘记异步函数调用? 但我想知道是否有比启动额外的辅助线程更简单的需求。
任何想法和/或链接将不胜感激! -戴夫
Scenario:
- My main (UI) thread (Thread "M") runs, and spins up a worker thread ("W") to control with some hardware.
- "W" wants to send progress notifications to "M" every so often.
- The notification-invocation can't block "W"... "W" needs to make the call and return immediately; "M" will process the notification async and not return anything to "W".
- "M" must notified by a callback running on thread "M".
- Must be able to pass data (don't worry about thread-safeness of data).
.NET has just such a facility in it's System.ComponentModel.AsyncOperation class, but I'm wanting to create cross-platform code, not just .NET or even strictly Win32 (though my 1st platform is native c++ on Win32).
Using Boost would be a plus.
I've read this:
Boost: Fire and forget asynchronous function call?
but am wondering if there's a simpler want than to spin up additional helper threads.
Any ideas and/or links would be greatly appreciated!
-Dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 Boost.Thread 那么您可以使用条件变量。
If you are using Boost.Thread then you can use a condition variable.
我将这样做:
编辑:请注意,使用互斥锁的要求是可选的。这将是最常见、最跨平台友好的解决方案,这就是我将其放在示例中的原因。如果“W”线程永不阻塞的要求是最强的要求,那么您可以用无锁数据结构替换列表+互斥锁,假设您的平台有一个无锁数据结构。
Here is how I would do it:
Edit: note that the requirement to use a mutex is optional. This would be the most common, most cross-platform friendly solution and that is why I put it in my example. If the requirement for the "W" thread to never block is the strongest requirement, then you can replace the list+mutex with a lock-free data structure, assuming you have one for your platform.