How does Mutex feel about Semaphore?

Add: OK, so I can separate the mutex and the semaphore, and I just want to know what my counter idea is right? namely Release minus one and WaitOne add one, only if the counter is greater than zero, it will allow to start. Is this statement correct?

I have code that works well: run first () second () third () in order.

I just want to know how a counter works in a semaphore? I know this is a counter. This is Release minus one, and WaitOne is one, only if the counter is greater than zero, it will allow you to start. Right?

However, I read a book about something else, Mutex, the book says that Mutex Waitone is minus one, and the release adds one, so mutexes are the opposite of semaphore? Right?

code:

using System; namespace Algorithm.MultiThread { class Semaphore { System.Threading.Semaphore s1, s2; public Semaphore() { s1 = new System.Threading.Semaphore(1, 5); s2 = new System.Threading.Semaphore(1, 5); //initialize as start counter 1 } public void first() { Console.WriteLine("First"); s1.Release(); // minus one } public void second() { s1.WaitOne(); //add one two times s1.WaitOne(); Console.WriteLine("Second"); s2.Release(); } public void third() { s2.WaitOne(); // add one two times s2.WaitOne(); Console.WriteLine("Third"); } public void startnum(object obj) { int i = (int)obj; switch (i) { case 1: first(); break; case 2: second(); break; case 3: third(); break; default: break; } } public static void test() { Semaphore s = new Semaphore(); System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum)); System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum)); System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum)); t1.Start(3); t2.Start(2); t3.Start(1); } } } 
+4
source share
2 answers

Mutex is basically a special case of a semaphore. One might think (although in reality this was not implemented as) a semaphore that starts with one and cannot be more than one.

Imagine Semaphore as a wrapper around an integer and a mutex as a wrapper around a boolean. It has only two states, free or blocked.

+5
source

A mutex is like having a semaphore with one thread allowed.

Mutex allows only one access to a resource at a time, while the semaphore can be configured to allow any predefined parallel access number to a resource or code snippet.

Edit:

Both can be used in different processes, if they are named.

+1
source

All Articles