How do I use while true in threads?
13,430
Solution 1
join
blocks the current thread to wait for another thread to finish. Since your t1
never finishes, your main thread waits for it indefinitely.
Edit:
To run two threads indefinitely and concurrency, first create the threads, and then wait for both:
int main() {
thread t1(Loop);
thread t2(SecondLoop);
t1.join();
t2.join();
}
Solution 2
To run Loop
and SecondLoop
concurrency, you have 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 current thread to wait the other thread finishes.
Author by
Purixi
Updated on June 16, 2022Comments
-
Purixi almost 2 years
Can anyone point me at the thing I try to do in this code, because
SecondLoop
thread is unreachable at all? It becomes reachable only if I removewhile(true)
loop.#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 why I use multithreading is because I need to get two loops running at the same time.