我认为在第一种选择中,必须非常小心,以避免同时访问数据(使用pthread_mutex )
请建议你将如何处理这个问题。
我真的很感谢你的帮助
非常感谢
发布于 2014-11-11 14:54:48
如果我没理解错的话,您计划让一个侦听器线程接收消息,并将它们分派到多个并发处理这些消息的线程。
在这里,一种可能的方法是使用共享queue:
push() the message on the queue:empty(),take the next element to process (front()``andpop()`)只需共享队列即可。您可以使用全局定义来实现这一点。但另一方面,尽可能避免使用全局变量/对象是一种好的做法。因此,您最好在创建和启动线程时动态实例化队列,并将对队列的引用传递给每个线程。
使用C++11 standard threads,它看起来有点像:
...
std::queue<my_message_class> work_to_do; // create queue
std::thread t1(listener, std::ref(work_to_do)); // launch listener
int n = max(2, std::thread::hardware_concurrency()-1); // maximize concurency for the hardware
std::vector<std::thread> workers;
for (int i = 0; i < n; i++) {
v.push_back(std::thread{ worker_function, std::ref(work_to_do) });
}
... // do something else and wait until it finishes
t1.join(); // wait until listner finishes
for (auto& x : workers) { // wait until all the worker threads finish.
x.join();
}
...其中void listener(std::queue<my_message_class>& q)和void worker(std::queue<my_message_class>& q)是要执行的函数。
当然,您也可以使用pthread来做类似的事情。但标准的优势在于它是平台无关的。
https://stackoverflow.com/questions/26858911
复制相似问题