How can I synchronize three threads?

后端 未结 6 1834
北恋
北恋 2021-01-16 10:44

My app consist of the main-process and two threads, all running concurrently and making use of three fifo-queues:

The fifo-q\'s are Qmain, Q1 and Q2. Internally the

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-16 11:32

    Use the debugger. When your solution with mutexes hangs look at what the threads are doing and you will get a good idea about the cause of the problem.

    What is your platform? In Unix/Linux you can use POSIX message queues (you can also use System V message queues, sockets, FIFOs, ...) so you don't need mutexes.

    Learn about condition variables. By your description it looks like your Qmaster-thread is busy looping, burning your CPU.

    One of your responses suggest you are doing something like:

    Q2_mutex.lock()
    Qmain_mutex.lock()
    Qmain.put(Q2.get())
    Qmain_mutex.unlock()
    Q2_mutex.unlock()
    

    but you probably want to do it like:

    Q2_mutex.lock()
    X = Q2.get()
    Q2_mutex.unlock()
    
    Qmain_mutex.lock()
    Qmain.put(X)
    Qmain_mutex.unlock()
    

    and as Gregory suggested above, encapsulate the logic into the get/put.

    EDIT: Now that you posted your code I wonder, is this a learning exercise? Because I see that you are coding your own FIFO queue class instead of using the C++ standard std::queue. I suppose you have tested your class really well and the problem is not there.

    Also, I don't understand why you need three different queues. It seems that the Qmain queue would be enough, and then you will not need the Qmaster thread that is indeed busy waiting.

    About the encapsulation, you can create a synch_fifo_q class that encapsulates the fifo_q class. Add a private mutex variable and then the public methods (put, get, clear, count,...) should be like put(X) { lock m_mutex; m_fifo_q.put(X); unlock m_mutex; }

    question: what would happen if you have more than one reader from the queue? Is it guaranteed that after a "count() > 0" you can do a "get()" and get an element?

提交回复
热议问题