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

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

问题描述

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

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.

自旋锁: 当您确实要使用互斥锁但不允许线程进入睡眠状态时,请使用自旋锁. 例如:OS内核中的中断处理程序必须永不休眠.如果这样做,系统将冻结/崩溃.如果需要从中断处理程序中将节点插入到全局共享链表中,请获取自旋锁-插入节点-释放自旋锁.

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天全站免登陆