Reputation: 477
what i want to do is create some threads and push them into a vector to launch them after some checks.
so here in my main i want to create theme as follow
int main()
{
Pont pont;
for (int k = 0; k <= 20; k++) {
std::thread th(crossBridge);
pont.threadsW.push_back(std::move(th));
}
pont.init();
return 0;
}
and launch theme here:
void WestToEast()
{
cout << "préparation du trafic vers l'est \n";
while (true) {
std::unique_lock<std::mutex> lock(mut);
while (!notified2) {
cond.wait(lock);
}
while (!threadsE.empty() && j < 10) {
j++;
""
" i want to launch theme here "
""
}
j = 0;
notified1 = true;
notified2 = false;
}
}
every suggestion is appreciated and also how to join theme once launched and deleted from the vector
ps: i just posted the concerned part of code
Upvotes: 2
Views: 126
Reputation: 6647
You can populate your vector with default constructed (empty) thread objects.
for (int k = 0; k<=20; k++)
pont.threadsW.push_back({}); // populate vector with empty thread objects
Once you have done your checks, associate each vector object with a thread function.
for (auto& th : pont.threadsW)
th = thread(crossBridge);
You are not really creating a thread and deferring it until it is launched.. Instead, the vector is populated with empty thread objects. The actual thread is created and starts running once you move the new thread into the vector thread object.
When you are done, call join()
on each thread object.
for (auto& th : pont.threadsW)
th.join();
If your thread function needs to be in a running state while you are doing your pre-launch checks, additional synchronization is needed where each thread is waiting for the all-clear signal before it can move on.
Upvotes: 3