Actually,the main scenerio is that : from main thread there are two thread running.By using conditional variable,two threads will be running and sleeping and then it will return to main thread.I mean I dont want different output pattern.just one pattern:from main->thread1->thread2->main. I have written a code for C thread.It shows the result I want sometimes and sometimes not.as for example,the output is:
I am in thread 1
before conditional wait
I am in thread 2
before conditional release
i am again in thread 2
i am again in thread 1
main exits here
The problem is sometimes "main exits here" does not execute.Please help me.It is to be noted that I cant use pthread_join().my code is given below
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t gLock;
pthread_cond_t gCondition;
pthread_mutex_t mLock;
pthread_cond_t mCondition;
void initialize()
{
pthread_mutex_init(&gLock, NULL);
pthread_cond_init (&gCondition, NULL);
pthread_mutex_init(&mLock, NULL);
pthread_cond_init (&mCondition, NULL);
return;
}
void * threadOne(void * msg)
{
printf("%s \n",(char*) msg);
printf("before conditional wait\n");
pthread_mutex_lock(&gLock);
pthread_cond_wait(&gCondition,&gLock);
pthread_mutex_unlock(&gLock);
printf("i am again in thread 1\n");
pthread_mutex_lock(&mLock);
pthread_cond_signal(&mCondition);
pthread_mutex_unlock(&mLock);
}
void * threadTwo(void * msg)
{
printf("%s\n",(char*)msg);
printf("before conditional release\n");
pthread_mutex_lock(&gLock);
pthread_cond_signal(&gCondition);
pthread_mutex_unlock(&gLock);
printf("i am again in thread 2\n");
}
int main()
{
pthread_t thread1;
pthread_t thread2;
char * msg1="I am in thread 1";
char * msg2="I am in thread 2";
initialize();
pthread_create(&thread1,NULL,threadOne,(void*) msg1);
pthread_create(&thread2,NULL,threadTwo,(void*) msg2);
pthread_mutex_lock(&mLock);
pthread_cond_wait(&mCondition,&mLock);
pthread_mutex_unlock(&mLock);
printf("main exits here");
return 0;
}
The problem is that you are using the condition variable incorrectly. A condition variable is just a notification mechanism, not a flag. It has no internal state other than the list of threads currently waiting. Consequently, if
main()
has not actually executed as far as thepthread_cond_wait()
call when the other threads callpthread_cond_signal()
then the signal is lost, andmain()
will wait forever.You need to use a separate flag associated with the condition variable.
main()
can then check this flag, and only wait if the flag is not set. Also, it must check this flag in a loop, to ensure that "spurious wakeups" are handled, wherepthread_cond_wait()
returns without a corresponding signal. The same applies to the notification betweenthreadOne
andthreadTwo
.