Niklas Hantke
Niklas Hantke

Reputation: 363

Start multiple threads without joining

(how) can i start multiple threads like this:

for (i = 0; i < 10; i++) {
   std::thread (myfunction, i, param2, param3);
}

without joining?

Upvotes: 11

Views: 21752

Answers (3)

Yan
Yan

Reputation: 386

Of course you can create some threads without joining them, just like what you do:

for (i = 0; i < 10; i++) {
  std::thread my_thread {myfunction, i, param2, param3};
}

Once a thread is created, it starts being scheduled to run or wait. However, I advise you not doing that.

The meaning of "join" is to require the current thread to wait for the thread you called join on. For example,

#include <iostream> 
#include <thread> 
using namespace std; 

// A dummy function 
void foo(int n) 
{ 
  cout << "This is a dummy function." << endl; 
}

// Another dummy function
void bar(char c) {
  cout << "This is another dummy function." << endl;
} 

int main() 
{
  thread foo_thread(foo, 2); 
  thread bar_thread(bar, 'x');

  foo_thread.join();  // wait for foo_thread to finish
  bar_thread.join();  // wait for bar_thread to finish

  return 0; 
} 

The main thread will sleep until the foo_thread and bar_thread finish.

If you remove foo_thread.join() and bar_thread.join(), the main thread may finish and return before foo and bar. This will cause your program crash. Because at the end of main function, destructors of foo_thread and bar_thread are invoked, and the destructor of std::thread will check whether this thread is joinable. If the thread is not detached, it is joinable. And if the thread is joinable, the destructor will invoke std::terminate(), so your program crashes.

Upvotes: 0

Felix Glas
Felix Glas

Reputation: 15524

Try this

for (int i = 0; i < 10; ++i) {
    std::thread{myfunction, i, param2, param3}.detach();
}

Or if you want to join the threads later, then put them in a std::vector.

std::vector<std::thread> v;
for (int i = 0; i < 10; ++i) {
    v.emplace_back(myfunction, i, param2, param3);
}

// Do something else...

for (auto& t : v) {
    t.join();
}

Upvotes: 18

Paul Evans
Paul Evans

Reputation: 27577

Simply don't call join(), detach() instead.

Upvotes: 7

Related Questions