本文介绍了Semaphore Vs Mutex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一点互斥和信号量。



我有一段代码

  int func $ b {
i ++;
return i;
}

i在外部声明为全局变量。
如果我创建计数信号量计数为3不会有竞争条件?这意味着我应该在这种情况下使用二进制信号量或互斥?



有人可以给我一些实用的方法,其中可以使用Mutex,关键部分和信号量。



可能我读了很多。最后我有点困惑了。可以有人清除思想。



P.S:我已经理解互斥和二进制信号量之间的主要差别是所有权。 。

解决方案

互斥和信号量之间的区别(我从来没有使用过CriticalSection) / p>


  • 使用条件变量时,其锁必须是互斥体。

  • 资源,你必须使用一个用可用资源数初始化的信号量,所以当你的资源不足,下一个线程阻塞。

  • 当使用1个资源或一些只能执行的代码你可以选择使用互斥量或用1初始化的信号量(这是OP的问题的情况)。

  • 当线程等待直到另一个线程发出信号时,你需要一个信号量初始化为0(等待线程做sem.p(),信令线程做sem.v())。


I was reading a bit of Mutex and semaphore.

I have piece of code

int func()
{
 i++;
 return i;
}

i is declared somewhere outside as a global variable.If i create counting semaphore with count as 3 won't it have a race condition? does that mean i should be using a binary semaphore or a Mutex in this case ?

Can somebody give me some practical senarios where Mutex, critical section and semaphores can be used.

probably i read lot. At the end i am a bit confused now. Can somebody clear the thought.

P.S: I have understood that primary diff between mutex and binary semaphore is the ownership. and counting semaphore should be used as a Signaling mechanism.

解决方案

Differences between mutex and semaphore (I never worked with CriticalSection):

  • When using condition variables, its lock must be a mutex.
  • When using more than 1 available resources, you must use a semaphore initialized with the number of available resources, so when your out of resources, the next thread blocks.
  • When using 1 resource or some code that may only be executed by 1 thread, you have the choice of using a mutex or a semaphore initialized with 1 (this is the case for OP's question).
  • When letting a thread wait until signaled by another thread, you need a semaphore intialized with 0 (waiting thread does sem.p(), signalling thread does sem.v()).

这篇关于Semaphore Vs Mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:01