It's a C++ program. There are 2 child thread and 2 queue.What I want to do is,
这是一个C ++程序。有2个子线程和2个队列。我想做的是,
- Push something to the queue 1 in the main thread.
- The child thread 1 pop from the queue 1 and process it, then push it to the queue 2.
- The child thread 2 pop from the queue 2 and process, then output the answer.
将某些内容推送到主线程中的队列1。
子线程1从队列1弹出并处理它,然后将其推送到队列2。
子线程2从队列2中弹出并处理,然后输出答案。
How can I make it thread-safe? I think about two ways,
如何使其线程安全?我想到两种方式,
- Use a thread-safe queue. But does it means that I shouldn't use the queue of STL?
- Write thread lock. But how can I write 2 locks in one thread and lock the different part? It really puzzles me. Need help!!!! Any suggestion would be appreciated a lot!
使用线程安全队列。但这是否意味着我不应该使用STL队列?
写线程锁。但是如何在一个线程中编写2个锁并锁定不同的部分?这让我很困惑。需要帮忙!!!!任何建议都会受到很多赞赏!
1 个解决方案
#1
You already said it. Lock the write and read access to every queue with a mutex. Queue 1 and 2 gets a mutex. It would be easy if you write your own push and pop function for the queues. Inside this function you could use std queues or else.
你已经说过了。使用互斥锁锁定对每个队列的写入和读取访问权限。队列1和2获取互斥锁。如果你为队列编写自己的push和pop函数会很容易。在此函数中,您可以使用std队列或其他。
#1
You already said it. Lock the write and read access to every queue with a mutex. Queue 1 and 2 gets a mutex. It would be easy if you write your own push and pop function for the queues. Inside this function you could use std queues or else.
你已经说过了。使用互斥锁锁定对每个队列的写入和读取访问权限。队列1和2获取互斥锁。如果你为队列编写自己的push和pop函数会很容易。在此函数中,您可以使用std队列或其他。