主意:
当线程A需要检查条件变量的状态时x
,它会先持有互斥锁,然后再检查变量的状态,如果发现无效则开始等待。
由于线程 A 当前具有互斥锁,因此线程 B 不会中断。一旦线程 A 等待,它将释放互斥锁。
然后线程 B 可以获取互斥体并做任何它想做的事情。
#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;
}
}
输出:
anisha@linux-trra:~> ./a.out
B: Not signaled yet. Value of x: 1
A: Thread A
Thread waits.
^C
然后它只是挂起。
我需要在这里更正什么,为什么?