Skip to content

Instantly share code, notes, and snippets.

@angleton
Forked from Cvar1984/async-parallel.cpp
Created February 19, 2023 11:29
Show Gist options
  • Save angleton/f95c9ab29dc731e8d9d3a5ed56030939 to your computer and use it in GitHub Desktop.
Save angleton/f95c9ab29dc731e8d9d3a5ed56030939 to your computer and use it in GitHub Desktop.
std::async
/**
* async multi threading with c++
* flag : -pthread -std=c++0x
*/
#include <iostream> // std::cout
#include <unistd.h> // sleep();
#include <future> // std::async
class MyClass {
public:
auto doStuffSoLong()->int
{
sleep(7);
std::cout << "1" << std::endl << std::flush; //dont buffer
return 0;
}
auto doAnotherStuff()->int
{
std::cout << "2" << std::endl << std::flush; //dont buffer
return 0;
}
auto doAnotherLongStuff(const std::string &param)->int
{
sleep(3);
std::cout << "3" << std::endl << std::flush; //dont buffer
return 0;
}
};
int main()
{
sleep(3); // give a time to open task manager
MyClass app;
auto thread1 = std::async(std::launch::async, &MyClass::doStuffSoLong, &app);
auto thread2 = std::async(std::launch::async, &MyClass::doAnotherStuff, &app);
auto thread3 = std::async(std::launch::async, &MyClass::doAnotherLongStuff, &app, "hello world");
if(thread1.get() == 0) std::cout << "thread 1 succes" << std::endl;
if(thread2.get() == 0) std::cout << "thread 2 succes" << std::endl;
if(thread3.get() == 0) std::cout << "thread 3 succes" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment