zoukankan      html  css  js  c++  java
  • 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实现

  • 相关阅读:
    [引]Windows Server 2003 : 服务器群集
    周国平:(爱情)永远未完成
    企业管理常用缩写术语之中英文对照表(含解释)
    微软相关中文网站
    陈安之:NAC神经链调正术
    学会不要再争吵
    Oracle基础学习四:字符串 数字 日期 等 相关函数
    贪多嚼不烂
    frameset 框架传值点滴
    陈安之成功的十个关键
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/13474400.html
Copyright © 2011-2022 走看看