C++多线程编程题

写在前面:最近练习C++多线程,从网上其他博客找的一些小编程题。代码是自己写的,主要是个人复习用,如果有问题,欢迎在评论区讨论。

1.编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

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

mutex mux;
condition_variable cv;

char aimChar = 'A';

void  print_ABC(char c) {
	for (int i = 0; i < 10; i++) {
		unique_lock<mutex> lock(mux);
		while(c != aimChar) cv.wait(lock);//注意这里必须要用while,不能是if
		cout << c ;
		aimChar = 'A' + (aimChar - 'A' + 1) % 3;
		cv.notify_all();
	}
}

int main() {
	thread thA(print_ABC, 'A');
	thread thB(print_ABC, 'B');
	thread thC(print_ABC, 'C');

	thA.join();
	thB.join();
	thC.join();
}

  1. 子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
using namespace std; 

mutex mux;
condition_variable cv;

string now = "child";

void child() {
	for (int i = 0; i < 10 * 50; i++) {
		unique_lock<mutex> lock(mux);
		while (now!="child") cv.wait(lock);
		if ( ( i + 1 )  %  10  ==  0) now = "father";
		cout << "子线程运行: " << i%10 +1 << endl;
		cv.notify_all();
	}
}



int main() {
	
	thread th(child);

	for (int i = 0; i < 100 * 50; i++) {
		unique_lock<mutex> lock(mux);
		while (now != "father") cv.wait(lock);
		if ( ( i + 1 ) % 100 == 0) now = "child";
		cout << "父线程运行: " << i%100 + 1 << endl;
		cv.notify_all();
	}

	th.join();
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值