Hello All,
I would like to know can we post more than one thread at a time.
I have code like below
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);
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, thrdFun1, argmsg2);
res = pthread_create(&thrd3, NULL, thrdFun1, argmsg3);
res = pthread_create(&thrd4, NULL, thrdFun1, 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);
}
}
here it does accept and sem_post serially to the thread than invoking all the threads at a time.
Do this kind of behaviour can be achived using posix semaphores ( posting to multiple threads)? or should i use any pthread api like pthread_broadcast etc..
your comments would help in understanding .
regards