How do I use while true in threads?

2020-07-13 13:22发布

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 remove while(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.

5条回答
三岁会撩人
2楼-- · 2020-07-13 13:34

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;

}

查看更多
等我变得足够好
3楼-- · 2020-07-13 13:38

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-07-13 13:41

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();
}
查看更多
Bombasti
5楼-- · 2020-07-13 13:50

.join() waits for the thread to end (so in this case if you break out of the while loops and exit the thread function)

查看更多
Ridiculous、
6楼-- · 2020-07-13 13:54

using while(true) is linked to the tread running , you should look for a way to exit that loop, use some sort of loop control

查看更多
登录 后发表回答