How can I check if thread is done, when using thread::detach

  c++

I am trying to make kind of "running check" to avoid running one function multiple times at once it is for my another project. I have to use while() and detach() , the problem is I don’t really know how can I check if thread is joinable(), because when I am not doing this this, the error comes out: Unhandled exception at 0x7632A842 in dasd.exe: Microsoft C++ exception: std::system_error at memory location 0x009BF614. but when I use code below I am getting no errors, but loop won’t work

#include <future>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;

void Thing() 
{
    std::this_thread::sleep_for(3s);
    std::cout << "donen";  
}
int main() 
{
    std::packaged_task<void()> task(Thing);
    auto future = task.get_future();

    std::thread ac(std::move(task));

    while (true) 
    {
        std::cout << ac.joinable() << std::endl;
        if (future.wait_for(1ms) == std::future_status::ready && ac.joinable()) 
        {
            ac.detach();
            std::cout << "goodn";
        }
        std::this_thread::sleep_for(1s);
    }
}

the output is:

1
1
1
done
1
good
0
0
.......

the question is: how can i make successful loop avoiding errors? I am trying for such as long time, and i think it is about something what i just don’t know…

Thank You in advance

Source: Windows Questions C++

LEAVE A COMMENT