Purpose: You can use semaphores to limit the number of threads that access a shared resource
Meaning: A semaphore is an object that controls access to a common resource. Before accessing a resource, the thread must obtain a license from the semaphore, and after accessing the resource, the thread must return the license to the semaphore. Once licensed, the total number of licenses available in the semaphore is reduced by 1, and once the license is released, the number of licenses in the semaphore increases by 1.
Only one permissible semaphore can be used to simulate a mutually exclusive lock.
Example:
What are the similarities and differences between the locks and semaphores?
(Here the lock refers to the mutex)
Difference:
Scope
Semaphore: Inter-process or between threads
Mutex: Between threads
Execution at lock-in
Semaphore: If the semaphore is value > 0, then other threads can perform the task. And after successful execution, value--, if value=0, then thread sem_wait causes the thread to block until Sem_post is released value++, other threads can be executed based on value.
Mutex: Only one object is locked (locking), and no other thread can access the locked object.
One is synchronous, one is mutually exclusive.
Semaphore: Used in multi-threaded multitasking synchronization, one thread completes an action by telling another thread about the semaphore, and the other thread is doing some action.
Mutex: Used in multi-threaded multitasking mutex. Once a thread occupies a resource, other threads cannot access it until the thread is unlock and other threads are available.
that is, the semaphore is not necessarily locked a certain resource, but the concept of the process, such as: There is a A, a, a two thread, B thread to wait for a thread to complete a task after the next step, the task does not necessarily lock a resource, but also to do some calculation or data processing and so on. The thread mutex is the concept of "lock a Resource", during which other threads cannot manipulate the protected data. In some cases the two are interchangeable .
Related articles:
Examples of mutex semaphores and multithreaded wait mechanisms in Java
PHP Semaphore Basic Usage Example detailed