二进制信号量和互斥量之间有区别吗?或者它们本质上是相同的?
当前回答
互斥对象有所有权,不像信号量。尽管在互斥量范围内的任何线程都可以获得一个未锁定的互斥量,并锁定对同一关键代码段的访问,但只有锁定了互斥量的线程才应该解锁它。
其他回答
厕所的例子是一个有趣的类比:
Mutex: Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue. Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library (A mutex is really a semaphore with value 1.) Semaphore: Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue. Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library
二进制信号量和互斥量的区别: 所有权: 信号量甚至可以从非当前所有者发出信号(发布)。这意味着您可以简单地从任何其他线程发布,尽管您不是所有者。
信号量是进程中的公共属性,它可以简单地由非所有者线程发布。 请用粗体字标出这个区别,这意味着很多。
“二进制信号量”是一种编程语言规避使用«信号量»,如«互斥量»。显然有两个非常大的区别:
你称呼他们的方式。 标识符的最大长度。
互斥锁用于阻塞关键区域,而信号量用于计数。
虽然二进制信号量可以用作互斥量,但互斥量是一个更具体的用例,因为只有锁定了互斥量的进程才应该解锁它。这种所有权限制使我们有可能对以下情况提供保护:
意外释放 递归死锁 任务死亡死锁
这些限制并不总是存在,因为它们降低了速度。在代码开发期间,您可以暂时启用这些检查。
例如,你可以在互斥锁中启用错误检查属性。错误检查互斥量返回EDEADLK,如果你试图锁定同一个互斥量两次,如果你解锁了一个不是你的互斥量,返回EPERM。
pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init (&mutex, &attr);
一旦初始化,我们可以将这些检查放在我们的代码中,就像这样:
if(pthread_mutex_unlock(&mutex)==EPERM)
printf("Unlock failed:Mutex not owned by this thread\n");
推荐文章
- 如何检查Python的操作系统?
- 在Swift中,什么相当于Objective-C的“@synchronized”?
- 信号量和监视器——有什么不同?
- 如何使用JavaScript找到操作系统的详细信息?
- 我如何检查操作系统与预处理器指令?
- 如何在没有操作系统的情况下运行程序?
- 线程之间共享哪些资源?
- Windows、Mac OS X和Linux是用什么语言编写的?
- 什么时候应该使用自旋锁而不是互斥锁?
- context . start前台服务()没有调用service . start前台()
- 在c#中使用全局互斥锁的好模式是什么?
- 什么是信号量?
- 什么是私有字节、虚拟字节、工作集?
- 用简单的术语解释什么是文件描述符?
- 开始操作系统开发有哪些资源?