C++11 Segmentation fault with std::promise

C++ std::promise Segmentation Fault

This code creates multiple threads and sends a promise& to them. It segfaults when they call promise::set_value to try and return data back to main.

Can anyone explain why this code produces a segmentation fault?

void workerFunc(promise<long>& prom) {

    long number = doInterestingThings();
    //SEGFAULT!!!
    prom.set_value(number);
    return;
}

The thread function. It segfaults at prom.set_value . Doesn't do it if I only create 1 thread.

int main (int argc, char** argv) {
    vector<promise<long>> promises;
    vector<future<long>> futures;
    vector<thread> workers;

Intialization.

    const int createThisMany = 6;
    for (int i = 0; i < createThisMany; i++) {
        promises.emplace_back();
        futures.push_back(promises.back().get_future());
        workers.emplace_back(workerFunc, std::ref(promises.back()));
    }

Creates all the threads and promise and future objects. Not included is the main loop where the vectors are monitored and the dead threads removed, etc.

Do promises and futures have to be synchronized, perhaps?

I'm using gcc 4.9 on Lubuntu 14.04


promises.emplace_back(); can cause vector reallocation and invalidation of all contained object locations (references, iterators). You have dangling references.

Move the promise into the code that will fullfil the promise after storing the future that will be sent to the consumer of the data.

Note that MSVC screws up some of the threading move of promise in 2013.


You cannot share promises. Move them instead:

 workers.emplace_back(workerFunc, std::move(promises.back());

And:

void workerFunc(promise<long> prom);

This means you probably don't need a vector of empty promises, either:

promise<long> pr;
futures.push_back(pr.get_future());
workers.emplace_back(workerFunc, std::move(pr));
链接地址: http://www.djcxy.com/p/30750.html

上一篇: 是否有使用线程池的std :: async的实现?

下一篇: C ++ 11分段错误,使用std :: promise