mercredi 2 mars 2016

Keeping reference alive after being passed to thread

I have a graph object that I am passing into a thread like this:

void MyClass::execute_subqueries(Graph& g, vector<query>&& queries) {
  for (size_t i = 0; i < queries.size(); i++) {
    threads.emplace_back(thread(my_thread, ref(g), queries[i]));
  }
}

I want to make a copy of the Graph object g and pass a reference to all the threads I'm starting in the for loop. I don't want to make a copy for each thread because the Graph is large and it's expensive to clone it.

The problem is that I can't figure out how to keep my Graph object alive. I think after I pass in the reference, the Graph object gets deallocated and my threads do not produce the result I expect.

I've tried something like this:

// Stores my graphs
vector<Graph> graphs;

void MyClass::execute_subqueries(Graph& g, vector<query>&& queries) {
  graphs.emplace_back(Graph(g));
  for (size_t i = 0; i < queries.size(); i++) {
    threads.emplace_back(thread(my_thread, ref(graphs.back()), queries[i]));
  }
}

This doesn't seem to work though.

Aucun commentaire:

Enregistrer un commentaire