Multithreaded single-reader single-writer fifo queue

前端 未结 4 1669
囚心锁ツ
囚心锁ツ 2020-12-29 14:22

I need a queue for passing messages from one thread (A) to another (B), however ive not been able to find one that really does what I want, since they generally allow adding

4条回答
  •  失恋的感觉
    2020-12-29 14:41

    • Why not use STL <list> or <deque> with a mutex around add/remove? Is the thread-safety of STL insufficient?

    • Why not create your own (singly/doubly) linked-list-node class that contains a pointer, and have the items to be added/removed inherit from that? Thus making additional allocation unnecessary. You just frob a few pointers in threadA::add() and threadB::remove() and you are done. (While you'd want to do that under a mutex, the blocking effect on threadA would be negligible unless you did something really wrong...)

    • If you're using pthreads, check out sem_post() and sem_wait(). The idea is that threadB can block indefinitely via sem_wait() until threadA puts something on the queue. Then threadA invokes sem_post(). Which wakes up threadB to do it's work. After which threadB can go back to sleep. It's an efficient way of handling asynchronous signaling, supporting things like multiple threadA::add()'s before threadB::remove() completes.

提交回复
热议问题