Site Tools


semaphore

Semaphore (synchronization)

Semaphores are a concept in multithreaded programming.

They behave somewhat like int value in that semaphores support two distinct well-known operatons (just like C integers). Namely value++ and value--. These operations increment or decrement the semaphore's value. The difference between semaphores and integers lies in how these operations behave when the value of value is exactly zero.

  1. If (value == 0), trying to do value-- will block the calling thread.
  2. If (value == 0), trying to do value++ will unblock a thread if there are any threads to unblock. The value in this case remains zero. Otherwise, the value is incremented as usual

Threads are free to call value++ or value-- at any time, but the semaphore forbids them from decrementing a value below zero. If you try, you get blocked and will have to be rescued by another thread.

Implementation

The structure of a semaphore can be therefore be understood like this:

struct Semaphore {
    int value;
    queue<int> blockedPids;
};

Usage

If you're writing a program that only has a single thread semaphores are completely useless to you. The only thing you can do with them is cause a deadlock by blocking your own thread - the main thread.

If you have two or more threads then you can use semaphores to solve one or two fundamental problems in multithreaded programming:

  1. Problem of synchronization
  2. Problem of mutual exclusion

Examples

These examples are use EasyMT, which is a library I wrote to easily illustrate multithreading concepts.

1. Basic synchronization

Sem sa = 1;
Sem sb = 0;
 
void a() {
    while (true) {
        wait(sa);
        print(RED "a");
        signal(sb);
    }
}
 
void b() {
    while (true) {
        wait(sb);
        print(GREEN "b");
        signal(sa);
    }
}
semaphore.txt ยท Last modified: by Ivan Janevski