简体   繁体   中英

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

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM