多线程顺序执行实现方式

多线程顺序执行实现方式

方式一 互斥锁

#include <time.h>
#include <unistd.h>

#include <iostream>
#include <mutex>
#include <thread>
using namespace std;

int flag = 1;
mutex mtx;

void PrintA() {
  for (;;) {
    unique_lock<mutex> locker(mtx);
    if (flag == 1) {
      cout << "A" << endl;
      flag = 2;
    }
  }
}

void PrintB() {
  for (;;) {
    unique_lock<mutex> locker(mtx);
    if (flag == 2) {
      cout << "B" << endl;
      flag = 3;
    }
  }
}

void PrintC() {
  for (;;) {
    lock_guard<mutex> locker(mtx);
    if (flag == 3) {
      cout << "C" << endl;
      flag = 1;
    }
  }
}

int main() {
  thread th1(PrintA);
  thread th2(PrintB);
  thread th3(PrintC);
  for (;;) {
    sleep(1);
  }
}

方式二 信号量

#include <semaphore.h>
#include <time.h>
#include <unistd.h>

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;

int flag = 1;
condition_variable con;
mutex mtx;
sem_t sem1;
sem_t sem2;
sem_t sem3;

void PrintA() {
  for (;;) {
    sem_wait(&sem1);
    cout << "A" << endl;
    sem_post(&sem2);
  }
}

void PrintB() {
  for (;;) {
    sem_wait(&sem2);
    cout << "B" << endl;
    sem_post(&sem3);
  }
}

void PrintC() {
  for (;;) {
    sem_wait(&sem3);
    cout << "C" << endl;
    cout << "=============" << endl;
    sem_post(&sem1);
  }
}

int main() {
  sem_init(&sem1, 0, 1);
  sem_init(&sem2, 0, 0);
  sem_init(&sem3, 0, 0);

  thread th1(PrintA);
  thread th2(PrintB);
  thread th3(PrintC);

  for (;;) {
    sleep(1);
  }
  sem_destroy(&sem1);
  sem_destroy(&sem2);
  sem_destroy(&sem3);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值