Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this use of std::promise thread safe?

Consider this code:

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

std::promise<int> prom;

void thr_func(int n)
{
    prom.set_value(n + 10);
}

int main()
{
    std::thread t{thr_func, 5};

    auto fut = prom.get_future();

    int result = fut.get();
    std::cout << result << std::endl;

    t.join();
}

The prom object is accessed concurrently and even though the standard says that set_value is atomic, I cannot find anything about get_future being atomic (or const).

Therefore I wonder whether it is correct to call get_future this way.

like image 341
Tootsie Avatar asked Sep 18 '25 01:09

Tootsie


1 Answers

You are right that the standard does not say anything about get_future being atomic. It is probably not safe to call it concurrently with set_value.

Instead, call get_future before thread creation. That guarantees it is called before set_value.

auto fut = prom.get_future();

std::thread t{thr_func, 5};

...
like image 157
LWimsey Avatar answered Sep 19 '25 16:09

LWimsey