Iam having a simple c program,
with one main thread
4 consumer threds
all consumebr threads are waiting on the same semaphore object.
my expectation is when main thread do the sem_post all consumer threads will come out of
blocked state and start printing the data which has been buffered by the main thread.
Is this right?
But in reality it does not unblock all the threads only first thread is coming out of the blocked state
and printing the result.
Can any body help me is this!
Code:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_MSG_LEN 256
sem_t sem1;
char msg1[MAX_MSG_LEN] = "1";
void *thrdFun1(void *arg);
void *thrdFun2(void *arg);
void *thrdFun3(void *arg);
void *thrdFun4(void *arg);
int main()
{
pthread_t thrd1,thrd2,thrd3,thrd4;
char argmsg1[] = "Thread1: ";
char argmsg2[] = "Thread2: ";
char argmsg3[] = "Thread3: ";
char argmsg4[] = "Thread4: ";
int res;
int thNum;
res = sem_init(&sem1,0,0);
res = pthread_create(&thrd1, NULL, thrdFun1, argmsg1);
res = pthread_create(&thrd2, NULL, thrdFun2, argmsg2);
res = pthread_create(&thrd3, NULL, thrdFun3, argmsg3);
res = pthread_create(&thrd4, NULL, thrdFun4, argmsg4);
while(1)
{
printf("Enter message to end to thread \n");
fgets(msg1,MAX_MSG_LEN,stdin);
sem_post(&sem1);
}
return 0; /* writing the comments */
}
void *thrdFun1(void *arg)
{
while(1)
{
sem_wait(&sem1);
printf("Iam %s message is %s\n",arg,msg1);
}
}
void *thrdFun4(void *arg)
{
while(1)
{
sem_wait(&sem1);
printf("Iam %s message is %s\n",arg,msg1);
}
}
void *thrdFun3(void *arg)
{
while(1)
{
sem_wait(&sem1);
printf("Iam %s message is %s\n",arg,msg1);
}
}
void *thrdFun2(void *arg)
{
while(1)
{
sem_wait(&sem1);
printf("Iam %s message is %s\n",arg,msg1);