Implement a high performance mutex similar to Qt's one

前端 未结 2 578
青春惊慌失措
青春惊慌失措 2021-02-04 10:59

I have a multi-thread scientific application where several computing threads (one per core) have to store their results in a common buffer. This requires a mutex mechanism.

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 11:42

    Not really an answer per definition, but depending on the specific task, a lock-free queue might help getting rid of the mutex at all. This would help the design, if you have multiple producers and a single consumer (or even multiple consumers). Links:

    • Though not directly C++/STL, Boost.Lockfree provides such a queue.
    • Another option is the lock-free queue implementation in "C++ Concurrency in Action" by Anthony Williams.
    • A Fast Lock-Free Queue for C++

    Update wrt to comments:

    Queue size / overflow:

    • Queue overflowing can be avoided by i) making the queue large enough or ii) by making the producer thread wait with pushing data once the queue is full.
    • Another option would be to use multiple consumers and multiple queues and implement a parallel reduction but this depends on how the data is treated.

    Consumer thread:

    • The queue could use std::condition_variable and make the consumer thread wait until there is data.
    • Another option would be to use a timer for checking in regular intervals (polling) for the queue being non-empty, once it is non-empty the thread can continuously fetch data and the go back into wait-mode.

提交回复
热议问题