Skip to content

Instantly share code, notes, and snippets.

@Cvar1984
Last active February 19, 2023 11:29
Show Gist options
  • Save Cvar1984/34428afdb88a96a53e5481550fb54d28 to your computer and use it in GitHub Desktop.
Save Cvar1984/34428afdb88a96a53e5481550fb54d28 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