Thursday, November 10, 2016

C++ threading Primitives:mutex, lock_guard, thread, async,future



#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <future>

using namespace std;

inline int f() { return 42; };
mutex m;

void access_shared_res()
{
 cout << " 1 thread in, endl cannot catch up" << endl;

 lock_guard<mutex> g(m);
 cout << " 1 thread passed " <<this_thread::get_id()<< endl;
 this_thread::sleep_for(chrono::seconds(5));
}

int main()
{
 cout << " main thread " << this_thread::get_id() << endl;
 thread  t1(access_shared_res);
 thread  t2(access_shared_res);
 t1.join();
 t2.join();

 std::future<int> f1 = std::async(std::launch::async, []() {return 8; });
 cout << f1.get() << endl;
 std::future<int> promise = std::async(std::launch::async, &f);
 cout << promise.get() << endl;

 std::string s;
 getline(cin, s);
    return 0;
}


No comments:

Post a Comment