Idea:
When the thread A needs to check the state of the condition variable x, it will first hold the mutex lock then check the variable’s state, if found invalid, it will start waiting.
There will be no interruptions from the thread B since thread A currently has the mutex. Once thread A waits, then it will release the mutex.
thread B can then acquire the mutex and do whatever the hell it wishes to.
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
pthread_mutex_t mutexLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * functionOfThreadA (void * ptr);
void * functionOfThreadB (void * ptr);
int x = 0;
int main ()
{
pthread_t threadA;
pthread_t threadB;
char *messageA = (char *) "Thread A"; // TODO
char *messageB = (char *) "Thread B";
int returnValueA;
int returnValueB;
returnValueA = pthread_create (&threadA, NULL, functionOfThreadA, (void*) messageA);
returnValueB = pthread_create (&threadB, NULL, functionOfThreadB, (void*) messageB);
pthread_join (threadA, NULL);
pthread_join (threadB, NULL);
exit (0);
}
void * functionOfThreadA (void * ptr)
{
char * message;
message = (char *) ptr;
std :: cout << "\nA: " << message << "\n";
while (1)
{
pthread_mutex_lock (&mutexLock);
if (x == 10)
{
std :: cout << "\nx == 10 : true, functionOfThread A: " << message << "\n";
}
else
{
std :: cout << "\nThread waits." << "\n";
pthread_cond_wait (&cond, &mutexLock);
std :: cout << "\nA:++ " << message << "\n";
}
pthread_mutex_unlock (&mutexLock);
return 0;
}
}
void * functionOfThreadB (void * ptr)
{
while (1)
{
char * message;
message = (char *) ptr;
pthread_mutex_lock (&mutexLock);
x = x + 1;
if (x == 10)
{
std :: cout << "\nfunctionOfThread B: " << message << "\n";
pthread_cond_signal (&cond);
}
else
{
std :: cout << "\nB: Not signaled yet. Value of x: " << x << "\n";
}
pthread_mutex_unlock (&mutexLock);
return 0;
}
}
Output:
anisha@linux-trra:~> ./a.out
B: Not signaled yet. Value of x: 1
A: Thread A
Thread waits.
^C
And then it simply hangs.
What do I need to correct here and why?
The problem has been discovered.
After issuing the signal, I need to get out of the loop. But before I do so, I also need to unlock the mutex. The added code in
functionOfThreadBhas been highlighted by the ****** in the program below.