Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel processes using semaphores in C

Tags:

c

semaphore

I have a big problem with semaphores in C. Here is the link to inspiration of my code: http://cse.unl.edu/~ylu/csce351/notes/Solution%20for%20Building%20H2O.pdf.

There are two similar codes for hydrogen and oxygen. This is the idea: There are processes generated for oxygen and hydrogen and they are created in different time. When there are 2 hydrogens and 1 oxygen they call function bond(). But they have to wait for them. After the condition is evaluated as false it is supposed to switch to another process (or at least that is how I understand it). But in my code it continues to the next command which causes that it won't wait to all processes that I need. It prints to output after every process that is created even if it is supposed to wait. Does anyone know know whats wrong there?

(I can post more of the code if this is not enough.)

OXYGEN CODE:(hydrogen is similar)

sem_wait(mutex);
if ((*hydrogen >=2) && (*oxigen>=1))
{
    (*count_c)++;
    *count_cur_h-=2;
    sem_post(hydrel);
    sem_post(hydrel);
    *count_cur_o-=1;
    sem_post(oxrel);
}
else
{
    (*count_c)++;
    sem_post(mutex);   // This is the place where it is supposed
                       // to release and continue to another process,
                       // but it goes to the next command.
}

sem_wait(oxrel);
bond();
sem_wait(barrier);

//semaphores are initialized like this:
sem_init(mutex,1,1);
sem_init(oxrel,1,1);
sem_init(hydrel,1,2);
sem_init(barrier,1,3);
like image 422
Michael Erik Avatar asked Nov 09 '22 15:11

Michael Erik


1 Answers

sem_post is not a blocking call. sem_wait is the blocking call. If the value of semaphore is zero when sem_wait is called, the function that called it will block. sem_post is used to release another thread that is blocking waiting on sem_wait when the semaphore value is zero, but it does not block itself. The sem_post call is used to 'wake up a thread waiting on sem-wait' but then continues onwards, and both threads will then run at the same time (if you have at least 2 logical CPUs). If you want the thread that called sem_post to block at that point you will need to do something else (like add yet another semaphore).

like image 164
ckolivas Avatar answered Nov 15 '22 12:11

ckolivas