c++多線程之順序調用類成員函數


一、場景(leetcode1114)

一個類中三個函數

public class Foo {
  public void one() { print("one"); }
  public void two() { print("two"); }
  public void three() { print("three"); }
}
三個不同的線程將會共用一個 Foo 實例。

線程 A 將會調用 one() 方法
線程 B 將會調用 two() 方法
線程 C 將會調用 three() 方法

二、c++11中promise實現

c++11中promise,promise和future成對出現,我們可以阻塞future 的調用線程,直到set_value被執行,因此我們可以用兩個promise實現三個函數的順序執行,代碼實現如下

#include <iostream>
#include <functional>
#include <future>
using namespace std;

class Foo
{
public:
    Foo();
    ~Foo();

    void first();
    void second();
    void third();

    void printFirst() {
        cout << "first"<<endl;
    }

    void printSecond() {
        cout << "second"<<endl;
    }

    void printThird() {
        cout << "third"<<endl;
    }

private:
    std::promise<void> p1;
    std::promise<void> p2;
};

Foo::Foo()
{
}

Foo::~Foo()
{
}

void Foo::first() {
     printFirst();
    p1.set_value();
}

void Foo::second() {
    p1.get_future().wait();
    printSecond();
    p2.set_value();
}

void Foo::third() {
    p2.get_future().wait();
    printThird();
}



int main()
{
    Foo *fo=new Foo();
    thread t1(&Foo::first,fo);
    thread t2(&Foo::second, fo);
    thread t3(&Foo::third, fo);
    t3.join();
    t2.join();
    t1.join();


    getchar();
    return 0;
}

三、互斥量mutex實現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM