This is borrowed form https://github.com/Yawolf/semaphores
Common Errors
The incorrect use of semaphores can result in several errors that are very difficult to detect.
In this case, execute a sem_post before a sem_wait may allow other proccesses execute a critical section simultaneously:
sem_open(semaphore,1,Sem),
sem_post(Sem),
%% CRITICAL SECTION
sem_wait(Sem).
Another common error is execute two sem_wait consecutively in a semaphore with value 1, the result is a deadlock and no process can continue executing:
sem_open(semaphore,1,Sem),
sem_wait(Sem),
%% CRITICAL SECTION
sem_wait(Sem).
Take care when are you closing the semaphore, maybe you close a semaphore at the end of a process but there are one or more processes using the same semaphore, this can result in serious errors:
Process 1
sem_open(semaphore,1,Sem),
sem_wait(Sem),
%% CRITICAL SECTION
sem_post(Sem),
sem_close(Sem).
Process 2
sem_open(semaphore,1,Sem),
sem_wait(Sem),
%% CRITICAL SECTION
sem_post(Sem),
sem_close(Sem).
The correct way is:
Process 1
sem_open(semaphore,1,Sem),
sem_wait(Sem),
%% CRITICAL SECTION
sem_post(Sem).
Process 2
sem_open(semaphore,1,Sem),
sem_wait(Sem),
%% CRITICAL SECTION
sem_post(Sem).
Main process
sem_open(semaphore,1,Sem),
process_call('process_1',[],[background(P1)]),
process_call('process_2',[],[background(P2)]),
process_join(P1), process_join(P2),
sem_close(Sem).
Remember that sem_open create a new semaphore or open the semaphore if it exists