Search
 
SCRIPT & CODE EXAMPLE
 

CPP

async multi thread

/**
 * 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;

}
Comment

PREVIOUS NEXT
Code Example
Cpp :: how to find factorial of number in c++ 
Cpp :: c++ multiline string 
Cpp :: how can I delete a substring from a string in c++? 
Cpp :: cpp vector popback 
Cpp :: executing an opencv c++ code 
Cpp :: DSA 2. Complexity Analysis Google drive Educative excellent courses!!!! [Educative.io] Competitive Programming in C++ The Keys to Success 
Cpp :: qt file explorer 
Cpp :: right shift in c++ 
Cpp :: dangling pointer in cpp 
Cpp :: cin c++ 
Cpp :: How to generate all the possible subsets of a set ? 
Cpp :: public method 
Cpp :: unique element in array in c 
Cpp :: even and odd numbers 1 to 100 
Cpp :: C++ insert character 
Cpp :: cpp compare strings 
Cpp :: set to vector c++ 
Cpp :: rc.local not running centos 6 
Cpp :: Common elements gfg in c++ 
Cpp :: varint index 
Cpp :: Bit Tricks for Competitive Programming c ++ 
Cpp :: c++ write number to registry 
Cpp :: turbo c++ easy programs 
Cpp :: find min and max in array c++ 
Cpp :: cout alternative c++ 
Cpp :: is variable sized array are not allowed in c++? 
Cpp :: cout two dimension array c++ 
Cpp :: ue4 c++ add tag 
Cpp :: rgb(100,100,100,0.5) validation c++ 
Cpp :: DMA c/c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =