写在前面:最近练习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();
}
- 子线程循环 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();
}