Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading