U
U
Uncle_Savva2021-05-25 19:25:52
C++ / C#
Uncle_Savva, 2021-05-25 19:25:52

How can I continue executing code without waiting for the thread to terminate?

I can't run multiple threads so that each of them outputs an individual number, because after starting the first thread, the code "freezes" and waits for the end of this first thread.

#include <iostream>
#include <thread>
#include <vector>;

using namespace std;

void go(int p) {
  while (1) {
    cout << p << endl;
  }
}

void main() {
  
  for (int i = 0; i <= 2; i++) {
    thread a(go, i);
    a.join();
    cout << 123;
  }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Denis Zagaevsky, 2021-05-25
@zagayevskiy

Save the streams somewhere, and then do a join on each of them. It is he who is waiting for completion.

J
jcmvbkbc, 2021-05-25
@jcmvbkbc

something like that:

#include <iostream>
#include <thread>
#include <vector>;

using namespace std;

void go(int p) {
  while (1) {
    cout << p << endl;
  }
}

void main() {
  thread *t[3];

  for (int i = 0; i <= 2; i++) {
    t[i] = new thread(go, i);
    cout << 123;
  }
  for (int i = 0; i <= 2; i++) {
    t[i]->join();
    delete t[i];
  }
}

A
Alexander Ananiev, 2021-05-25
@SaNNy32

Use the detach() method instead of join.

M
maaGames, 2021-05-26
@maaGames

join - waits for the thread to complete
detach - unbinds the thread and lets it float
freely

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question