物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

C++のstd::asyncでメンバー関数を使ったマルチスレッド処理

#include <future>
#include <mutex>
#include <iostream>

std::mutex mtx3;

class MyClass3 {
    int long_calc1(int j) {

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "1 a" << std::endl;
        mtx3.unlock();

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "1 b" << std::endl;
        mtx3.unlock();

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "1 c" << std::endl;
        mtx3.unlock();
        return 0;
    }
    int long_calc2(int j) {

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "2 a" << std::endl;
        mtx3.unlock();

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "2 b" << std::endl;
        mtx3.unlock();

        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        mtx3.lock();
        std::cout << "2 c" << std::endl;
        mtx3.unlock();
        return 0;
    }
public:
    void run() {
        auto f1 = std::async(std::launch::async, &MyClass3::long_calc1, this, 1);
        auto f2 = std::async(std::launch::async, &MyClass3::long_calc2, this, 1);

        f1.get();
        f2.get();
    }
};

int main() {
    MyClass3 m;
    m.run();
    return 0;
}