Why i am getting No associated state error in below example. Could anyone tell any reason?

Advertisements

In below program i am getting error std::future_error: No associated
state error.could anyone help why i am facing this error

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

void task(int& var, std::future<int>& refFuture)
{
    std::packaged_task<int()> mytask{ [&](){var = 25; return var;}};
    auto future = mytask.get_future();
    mytask.make_ready_at_thread_exit();
    refFuture = std::move(future);
}

int main()
{
    int variable = 10;
    std::future<int> future;
    std::thread t1(task, std::ref(variable), std::ref(future));
    std::future_status status = future.wait_for(std::chrono::seconds(0));
    if(status == std::future_status::ready)
    {
        int myOutput = future.get();
        std::cout << "Myoutput :" <<  myOutput << std::endl;
    }

    t1.join();
}

>Solution :

You are not waiting for the thread to actually execute refFuture = std::move(future); before you wait on future in the main thread, so the future in main does not have any associated state to wait on at that point.

I am not sure what you are intending to do here, but you are supposed to prepare the std::packaged_task in the main thread, obtain the future from it in the main thread as well and then move the std::packaged_task into the thread to execute it there (per operator() or per make_ready_at_thread_exit). See e.g. the example at https://en.cppreference.com/w/cpp/thread/packaged_task/packaged_task.

Leave a ReplyCancel reply