mercredi 6 avril 2016

Threading - Is there a better way to code?

I was trying to do a sample threading program, where the spawning of thread is in a while loop. I DO NOT want to generate multiple number of threads. The while loop should keep on running, irrespective of whether the thread completed execution or not. There is a call to the .get() function of the above thread within the while loop. Again, this has to be called only when the thread executed correctly.

My code is given below:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

int thread(int varJ)
{
        std::cout<<"\t\t"<<varJ<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        return varJ;  
}

int main()
{
    int varI = 0;
    std::future<int> future = std::async(std::launch::async, [](){return 0;});
    std::future_status status;
    bool flag = false;

    while(1)
    {
        status = future.wait_for(std::chrono::milliseconds(0));
        if(status == std::future_status::ready && !flag)
        {
            future = std::async(std::launch::async, thread, varI);
            flag = true;
        }
        status = future.wait_for(std::chrono::milliseconds(0));
        if(status == std::future_status::ready && flag)
        {
            std::cout << "\t result is " << future.get() << '\n';
            future = std::async(std::launch::async, [](){return 0;});
            flag = false;
        }
        varI++;
    }
}

The output obtained:

    0
 result is 0
    865
 result is 865
    1723
 result is 1723
    2632
 result is 2632
    3590
 result is 3590
    4551
 result is 4551
    5509
 result is 5509

The output is as I expected it to be. But is this the way to code or is there a better way?

I am not pleased to use a flag in between the code, calling future.wait_for a lot many times and especially using the dummy thread that returns 0.

Aucun commentaire:

Enregistrer un commentaire