I am trying to learn process synchronization , I am trying semaphore,
My code snippet is as below:
#include <semaphore.h>
#include <unistd.h>
#include <iostream>
#include <thread>
using namespace std;
sem_t s,s1;
void odd(int& value)
{
while (value<10)
{
if(sem_wait(&s) == 0)
{
cout << "odd thread: " <<" process id: "<< getpid() <<" thread id: "<< this_thread::get_id()<<" value: "<<value<<'\n';
value++;
sem_post(&s1);
}
}
}
void even(int& value)
{
while (value < 11)
{
if(sem_wait(&s1) == 0)
{
cout << "even thread: " <<" process id: "<< getpid() <<" thread id: "<< this_thread::get_id()<<" value: "<<value<<'\n';
value++;
sem_post(&s);
}
}
}
int main()
{
int value = 1;
//sem_t s,s1;
sem_init(&s,0,1);
sem_init(&s1,0,0);
pid_t pid = fork();
if(pid < 0)
cout<<"Fork failedn";
else
{
if(pid)
{
cout<<"Parent process creating odd thread, parent process id: "<<getpid()<<'n';
odd(value);
}
else
{
cout<<"Child process creating even thread, child process id: "<<getpid()<<'n';
even(value);
}
}
return EXIT_SUCCESS;
}
Only the parent process is able to execute odd function , Even function is not getting executed, sorry for asking a very basic question , but since I am beginner to C++ , I am facing this problem , please suggest if I am doing something wrong.
I was expecting that the parent and child process should be able to execute the respective odd and even functions
Pramod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.