Reputation: 19
I'm having trouble with threads synchronization on Linux. I must generate the process hierarchy from this picture ( this part i managed to do).
But next I have to synchronize threads from different processes. The process P2 must create 6 threads and the process P6 must create 5 threads. And then the thread 5 from P2 must only start after the thread 3 from P6 has completed. I use conditional variables, but while I'm waiting for the thread 3 from P6 to end, process 2 remain blocked and I never reach to process 6 to create his threads. The function info is used to display the beginning and the end of the thread. I cannot use sleep or usleep
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
pthread_cond_t p2_t4=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER;
int end=-1;
void* function(void* arg)
{
int* nrth=(int*) arg;
info(BEGIN,6,*nrth);
info(END,6,*nrth);
pthread_mutex_lock(&lock1);
if(*nrth==3)
{
end=1;
pthread_cond_signal(&p2_t4);
}
pthread_mutex_unlock(&lock1);
return 0;
}
void* function2(void* arg)
{
int* nrth=(int*) arg;
pthread_mutex_lock(&lock1);
if(*nrth==4)
{
while(end==-1)
pthread_cond_wait(&p2_t4,&lock1);
}
pthread_mutex_unlock(&lock1);
info(BEGIN,2,*nrth);
info(END,2,*nrth);
return 0;
}
int main()
{
pthread_t threads[6];
int index[5];
pthread_t threads2[7];
int index2[7];
if(fork()!=0)
{
//info(BEGIN,1,0);
wait(NULL);
if(fork()!=0)
{
wait(NULL);
}
else
{
//info(BEGIN,3,0);
if(fork()!=0)
{
wait(NULL);
if(fork()!=0)
{
wait(NULL);
}
else
{
//info(BEGIN,6,0);
for(int i=1; i<=5; i++)
{
index[i]=i;
pthread_create(&threads[i],NULL,function,&index[i]);
}
for(int i=1; i<=5; i++)
{
pthread_join(threads[i],NULL);
}
//info(END,6,0);
//info(END,3,0);
//info(END,1,0);
}
}
else
{
//info(BEGIN,5,0);
//info(END,5,0);
}
}
}
else
{
//info(BEGIN,7,0);
wait(NULL);
for(int i=1; i<=6; i++)
{
index2[i]=i;
pthread_create(&threads2[i],NULL,function2,&index2[i]);
}
for(int i=1; i<=6; i++)
{
pthread_join(threads2[i],NULL);
}
if(fork()!=0)
{
wait(NULL);
if(fork()!=0)
{
wait(NULL);
}
else
{
//info(BEGIN,7,0);
//info(END,7,0);
//info(END,2,0);
}
}
else
{
//info(BEGIN,4,0);
//info(END,4,0);
}
}
return 0;
}
Upvotes: 0
Views: 394
Reputation: 136218
To generate that process tree the main process must do 2 calls to fork
to create 2 child processes. This code blocks the main process after the first fork
. The process creating code must be redone.
The mutexes and condition variables are not shared between the processes because each process has its own private address space. The mutexes and condition variables must be placed in shared memory in order to be shared across processes. Alteratively, use POSIX semaphores.
Upvotes: 1