多线程利用条件变量打印AB,ABC,奇偶数
1、条件变量
条件变量是多线程同步的一种方式。
2、两个线程打印ABAB
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 2
pthread_cond_t Aready = PTHREAD_COND_INITIALIZER; // A是否ready的条件
pthread_cond_t Bready = PTHREAD_COND_INITIALIZER; // B是否ready的条件
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
string nextchar = "A";
void* printerA(void*)
{
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (nextchar != "A") {
pthread_cond_wait(&Aready, &mutex);
}
cout << nextchar;
nextchar = "B";
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&Bready);
}
pthread_exit((void*) 1);
}
void* printerB(void*)
{
for(int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (nextchar != "B") {
pthread_cond_wait(&Bready, &mutex);
}
cout << nextchar;
nextchar = "A";
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&Aready);
}
pthread_exit((void*) 2);
}
int main ()
{
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
// 初始化并设置线程为可连接的(joinable)
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], NULL, printerA, NULL);
pthread_create(&threads[1], NULL, printerB, NULL);
// 删除属性,并等待其他线程
pthread_attr_destroy(&attr);
for( i=0; i < NUM_THREADS; i++ ){
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
cout << "Main: program exiting." << endl;
pthread_exit(NULL);
}