How to use true in streams?

Can someone tell me what I'm trying to do in this code because the SecondLoop stream SecondLoop unreachable at all? It only becomes available if I delete the while(true) .

 #include <iostream> #include <thread> using namespace std; void Loop() { while(true) { (do something) } } void SecondLoop() { while(true) { (do something) } } int main() { thread t1(Loop); t1.join(); thread t2(SecondLoop); t2.join(); // THIS THREAD IS UNREACHABLE AT ALL! return false; } 

The reason I use multithreading is because I need to run two loops at the same time.

+5
source share
5 answers

join blocks the current thread to wait for another thread to complete. Since your t1 never ends, your main thread waits forever for it.

Edit:

To start two threads unlimited and concurrency, first create threads, and then wait for both:

 int main() { thread t1(Loop); thread t2(SecondLoop); t1.join(); t2.join(); } 
+14
source

To run Loop and SecondLoop concurrency, you need to do something like:

 #include <iostream> #include <thread> void Loop() { while(true) { //(do something) } } void SecondLoop() { while(true) { //(do something) } } int main() { std::thread t1(Loop); std::thread t2(SecondLoop); t1.join(); t2.join(); } 

as join block the current thread to wait for another thread to finish.

+2
source

.join () expects the thread to complete (so in this case, if you exit the while loops and exit the stream function)

0
source

using the while (true) associated with the tread, you should look for a way to exit this loop, use some kind of loop control

0
source

Based on my comment and what @Nidhoegger answered, I suggest:

 int main() { thread t1(Loop); thread t2(SecondLoop); // Your 2 threads will run now in paralel // ... <- So some other things with your application // Now you want to close the app, perhaps all work is done or the user asked it to quit // Notify threads to stop t1running = false; t2running = false; // Wait for all threads to stop t1.join(); t2.join(); // Exit program return false; 

}

0
source

Source: https://habr.com/ru/post/1234851/


All Articles