Monday, December 7, 2020

Using std::async in C++

/*
* aysn_test.cpp
*
*/
#include <iostream>
#include <algorithm>
#include <future>

using namespace std;

struct X{
void thread_func(int o){
cout<< "thread func " <<o <<endl;
}
};
int thread_func(int o){
cout<< "thread func " <<o <<endl;
return 100+o;
}
int main(){

X x;

/**
* synchronous call -> next line will not be executed untill
* the thread function is executed. so "thread func 1" will be printed
* first followed by "after ->async(thread_func,1)"
**/
auto a = async(&X::thread_func,&x,1);
cout<< "after ->async(thread_func,1)" <<endl;

/**
* asynchronous call -> next line will be executed mostly even before
* the thread function is executed. so "thread func 2" will be printed
* after "after ->async(std::launch::async,thread_func,2)"
*
* a1.get() will get the returned value of the thread, if the thread
* function has not been scheduled it will wait until the thread is
* scheduled and thevalue is returned
**/
auto a1 = async(std::launch::async,thread_func,2);
cout<< "after ->async(std::launch::async,thread_func,2)" <<endl;
std::cout << a1.get() << '\n';

/**
* asynchronous call -> next line will be executed mostly even before
* the thread function is executed. so "thread func 3" will be printed
* only after "after ->async(std::launch::deferred,thread_func,3"
*
* thread function will be scheduled only after a2.wait() or a2.get()
* is called. so to schedule and get the return value wait() or get()
* has to be called otherwise thread will never be executed(thats why
* its lazy evaluation)
**/
auto a2 = async(std::launch::deferred,thread_func,3);
cout<< "after ->async(std::launch::deferred,thread_func,3)" <<endl;

//a2.wait();
//std::cout << a2.get() << '\n';;

}

compile command in linux
"g++ aysn_test.cpp -lpthread"

Output::
after ->async(thread_func,1)
thread func 1
after ->async(std::launch::async,thread_func,2)
thread func 2
102
after ->async(std::launch::deferred,thread_func,3)
thread func 2 ----a2.wait() or std::cout << a2.get() << '\n';;
103 ----std::cout << a2.get() << '\n';;

No comments:

Post a Comment

Simple dlopen-example

        A simple sample for checking whether a .so in Linux both dynamically linked & dynamically loaded-linked in a process will share ...