什么时候应该使用互斥量,什么时候应该使用信号量 [英] When should we use mutex and when should we use semaphore

查看:68
本文介绍了什么时候应该使用互斥量,什么时候应该使用信号量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候应该使用互斥锁,什么时候应该使用信号量?

When should we use mutex and when should we use semaphore ?

推荐答案

这里是我记得什么时候用什么 -

Here is how I remember when to use what -

信号量:当您(线程)想睡觉直到其他线程告诉您醒来时,请使用信号量.信号量向下"发生在一个线程(生产者)中,而信号量向上"(对于同一个信号量)发生在另一个线程(消费者)中例如:在生产者-消费者问题中,生产者想要休眠直到至少一个缓冲槽为空——只有消费者线程可以判断缓冲槽何时为空.

Semaphore: Use a semaphore when you (thread) want to sleep till some other thread tells you to wake up. Semaphore 'down' happens in one thread (producer) and semaphore 'up' (for same semaphore) happens in another thread (consumer) e.g.: In producer-consumer problem, producer wants to sleep till at least one buffer slot is empty - only the consumer thread can tell when a buffer slot is empty.

互斥:当您(线程)想要执行不应由任何其他线程同时执行的代码时,请使用互斥锁.互斥向下"发生在一个线程中,而互斥向上"必须稍后发生在同一线程中.例如:如果您要从全局链表中删除一个节点,则在删除该节点时,您不希望另一个线程乱用指针.当你获取了一个互斥量并且正忙着删除一个节点时,如果另一个线程试图获取同一个互斥量,它就会进入休眠状态,直到你释放这个互斥量.

Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time. Mutex 'down' happens in one thread and mutex 'up' must happen in the same thread later on. e.g.: If you are deleting a node from a global linked list, you do not want another thread to muck around with pointers while you are deleting the node. When you acquire a mutex and are busy deleting a node, if another thread tries to acquire the same mutex, it will be put to sleep till you release the mutex.

自旋锁:当您真的想使用互斥锁但不允许您的线程休眠时,请使用自旋锁.例如:操作系统内核中的中断处理程序绝不能休眠.如果这样做,系统将冻结/崩溃.如果需要从中断处理程序向全局共享链表插入节点,获取自旋锁-插入节点-释放自旋锁.

Spinlock: Use a spinlock when you really want to use a mutex but your thread is not allowed to sleep. e.g.: An interrupt handler within OS kernel must never sleep. If it does the system will freeze / crash. If you need to insert a node to globally shared linked list from the interrupt handler, acquire a spinlock - insert node - release spinlock.

这篇关于什么时候应该使用互斥量,什么时候应该使用信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆