我正在尝试编写一个利用 3 个线程并打印 0,1,2,3,4,5,.... 等等的程序。
线程 1 - 打印 0,3,6,9 等等
线程 2 - 打印 1,4,7,10 等等
线程 3 - 打印 2,5,8,11 等等
有人可以帮我写代码吗?
最佳答案
这里可能有更好的解决方案
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
using namespace std;
#define MAX 10
condition_variable cv1, cv2, cv3;
mutex m1;
int i;
void function1()
{
while (i < MAX) {
unique_lock<mutex> lock(m1);
cv1.wait(lock);
cout << i << endl;
i++;
lock.unlock();
cv2.notify_one();
}
}
void function2()
{
while (i < MAX) {
unique_lock<mutex> lock(m1);
cv2.wait(lock);
cout << i << endl;
i++;
lock.unlock();
cv3.notify_one();
}
}
void function3()
{
while (i < MAX) {
unique_lock<mutex> lock(m1);
cv3.wait(lock);
cout << i << endl;
i++;
lock.unlock();
cv1.notify_one();
}
}
int main()
{
thread t3(function3);
thread t1(function1);
thread t2(function2);
cv1.notify_one();
t1.join();
t2.join();
t3.join();
getchar();
return 0;
}
关于c++ - 具有 3 个线程的多线程程序,可打印数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11880483/