到Mutex还是不Mutex? [英] To Mutex or Not To Mutex?
问题描述
如果我只有一个读卡器和一个写卡器,我需要互斥吗?读取器从队列中接收下一个命令( food.front()
),并根据该命令执行任务。命令执行后,它将弹出命令。队列中的作者将命令推送到队列上( food.push()
)。
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 command. After the command is executed, it pops off the command. The writer to the queue pushes commands onto the queue (food.push()
).
互斥?我的读者(消费者)只执行如果 food.size()> 0
。我使用读取器线程和发送线程。
Do I need a mutex? My reader (consumer) only executes if food.size() > 0
. I am using a reader thread and send thread.
推荐答案
互斥体在多线程环境中使用。
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.
这篇关于到Mutex还是不Mutex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!