How can one in this simple example guarantee that the
a->push_back(i)
happens in the order in which the threads are started? So a contents would be {1,2,3}.
#include <vector>
#include <thread>
void do_stuf(int i,std::vector<int> * a)
{
//do very long stuff
a->push_back(i);
}
int main()
{
std::vector<int> tmp;
std::thread t1(do_stuf,1,&tmp);
std::thread t2(do_stuf,2,&tmp);
std::thread t3(do_stuf,3,&tmp);
t1.join();
t2.join();
t3.join();
}
One way is to pass the threads a pointer or reference to the place you want them to store their result (and make sure it remains allocated for the threads lifetime), like this:
It isn’t clear from your example what you are trying to achieve, but have you had a look at std::promise and std::future and figured out what they do? They may be what you want.
(The trouble with vector::push_back in this context is that it isn’t thread-safe. It may overwrite the same element if two push_backs executions overlap, or it may reallocate the array moving the storage location of all the elements.)