日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++11多线程编程-两个进程轮流打印1~100

發布時間:2024/4/18 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++11多线程编程-两个进程轮流打印1~100 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這是經典的同步互斥問題,

遵循原則:

1、條件變量需要鎖的保護;
2、鎖需要條件變量成立后,后重新上鎖;

參考代碼:

//notify_one()(隨機喚醒一個等待的線程) //notify_all()(喚醒所有等待的線程) //Create By@herongwei 2019/09/10#include <bits/stdc++.h> #include <mutex> #include <thread> #include <condition_variable> using namespace std;std::mutex data_mutex;//互斥鎖 std::condition_variable data_var;//條件變量 bool flag = true; void printfA() {int i = 1;while(i <= 100) {//休息1秒//std::this_thread::sleep_for(std::chrono::seconds(1));std::unique_lock<std::mutex> lck(data_mutex);data_var.wait(lck,[]{return flag;});//等待flag=true才打印奇數std::cout<<"A " << i <<endl;i += 2;flag = false;data_var.notify_one();} }void printfB() {int i = 2;while(i <= 100) {std::unique_lock<std::mutex> lck(data_mutex);data_var.wait(lck,[]{return !flag;});//等待flag=false才打印偶數std::cout<<"B " << i <<endl;i += 2;flag = true;data_var.notify_one();} } int main() {// freopen("in.txt","r",stdin);std::thread tA(printfA);std::thread tB(printfB);tA.join();tB.join();return 0; }

?

思路2:
C++ 11,VS2019
使用了unique_lock,條件變量
條件變量的wait(), notify_one()
wait()中使用了lambda表達式
代碼
#include <iostream>
#include <vector>
#include <thread>
#include <list>
#include <mutex>

using namespace std;

bool flag = true;

class A
{
public:

? ? void print1()
? ? {
? ? ? ? while (true)
? ? ? ? {
? ? ? ? ? ? std::unique_lock<std::mutex> lock1(print_mutex);
? ? ? ? ? ? data_var.wait(lock1, [] {return flag; });
? ? ? ? ? ? cout << "thread: " << std::this_thread::get_id() << " print: " << "A" << endl;

? ? ? ? ? ? flag = false;
? ? ? ? ? ? data_var.notify_one();
? ? ? ? }
? ? }

? ? void print2()
? ? {
? ? ? ? while (true)
? ? ? ? {
? ? ? ? ? ? std::this_thread::sleep_for(std::chrono::seconds(1));

? ? ? ? ? ? std::unique_lock<std::mutex> lock2(print_mutex);

? ? ? ? ? ? data_var.wait(lock2, [] {return !flag; });
? ? ? ? ? ? cout << "thread: " << std::this_thread::get_id() << " print: " << "B" << endl;

? ? ? ? ? ? flag = true;
? ? ? ? ? ? data_var.notify_one();
? ? ? ? }
? ? }

private:

? ? std::mutex print_mutex;
? ? std::condition_variable data_var;
};


int main()
{
? ? A myobj_a;

? ? std::thread print1(&A::print1, &myobj_a);
? ? std::thread print2(&A::print2, &myobj_a);

? ? print1.join();
? ? print2.join();

? ? return 0;
}

總結

以上是生活随笔為你收集整理的C++11多线程编程-两个进程轮流打印1~100的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。