To Mutex or Not To Mutex?

后端 未结 5 2074
眼角桃花
眼角桃花 2020-12-21 00:43

Do I need a mutex if I have only one reader and one writer? The reader takes the next command (food.front()) from the queue and executes a task based on the com

5条回答
  •  自闭症患者
    2020-12-21 01:14

    A mutex is used in multi-threaded environments. I don't see mention of threads in your question, so I don't see a need for a mutex.

    However, if we assume by reader and writer you mean you have two threads, you need to protect mutual data with a mutex (or other multi-threaded protection scheme.)

    What happens when the queue has items, and the reader thread pops something off while the writer thread puts something on? Disaster! With a mutex, you'll be sure only one thread is operating on the queue at a time.

    Another method is a lock-free thread-safe queue. It would use atomic operations to ensure the data isn't manipulated incorrectly.

提交回复
热议问题