我可以使用 boost::threadpool 作为“线程安全队列”吗?
我需要的实际上是一个线程安全的队列结构,其中多个客户端不断将数据转储到队列中,一个工作线程不断处理并弹出队列,
STL或Boost中是否存在任何完善的解决方案?
我现在考虑使用 Boost::threadpool 来做到这一点。只需将并行线程数设置为 1,每当客户端有新消息到达时,任务函数的输入参数就会更改。这是否有意义,是否有任何我尚未预料到的限制?
What I need is actually a thread-safe queue structure, where multiple clients keep dumping data into the queue and one working thread keeps processing and popping the queue
is there any well-established solution existing in STL or Boost?
I now think about using Boost::threadpool to do this. Simply set the number of parallel threads to be 1, the input parameter of task function is changed every time new message arrives from a client. Does this make sense, is there any limitation that I have not yet anticipated here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在boost中有一个消息队列类,这就是您所需要的:线程安全队列。
消息队列是进程间通信广泛使用的概念。消息队列是线程安全的队列,其主要特点是它会阻塞从空队列中读取数据并等待数据出现在其中。在该 boost 类中,还支持定时等待,并且在队列已满时阻塞写入器。
In boost there is a message queue class, that is what you need: a thread-safe queue.
Message queues is a widely-used concept for interprocess communication. A message queue is thread-safe queue, which key feature is that it blocks on reading from empty queue and waits for data to appear in it. In that boost class, timed waits are also supported, as well as blocking the writer if the queue is full.
如果您在单进程应用程序中需要这样的框架,boost::asio::io_service 应该就足够了。这是一个使用 boost::thread 和 boost::asio::io_service 的工作框示例类。
使用:-
实现 IWorkerThreadJob 接口。
从多个客户端调用 processJob 方法。
这里 boost::asio::io_service 充当线程安全队列。
If you need such a framework in a single process application, boost::asio::io_service should be sufficient. Here is a working box sample class using boost::thread and boost::asio::io_service.
Use:-
Implement IWorkerThreadJob interface.
Call processJob method from multiple clients.
Here boost::asio::io_service acts as a thread safe queue.
如果您使用的是 Windows,则可以在 ppl.h 中使用并发队列(VS2010 的新功能)。如果您不在 Windows 上,您可以使用 Intel 线程构建块中的并发_queue.h。
Anthony Williams 还有一个基于条件变量的队列 在他的博客上,这很好。
If you are on Windows you can use concurrent_queue in ppl.h (new for VS2010). If you aren't on windows you can use concurrent_queue.h in Intel's thread building blocks.
Anthony Williams also has a queue based on the condition variable on his blog which is good.