【Linux】多线程利用条件变量打印AB,ABC,奇偶数

多线程利用条件变量打印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);
}
                     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bible_reader

如果觉得文章有用,欢迎打赏支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值