如何在线程中使用true?

Pur*_*ixi 5 c++ multithreading c++11

任何人都可以指出我在这段代码中尝试做的事情,因为SecondLoop线程根本无法访问?只有删除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;
}
Run Code Online (Sandbox Code Playgroud)

我使用多线程的原因是因为我需要同时运行两个循环.

Sin*_*all 14

join阻止当前线程等待另一个线程完成.由于你t1永远不会完成,你的主线程无限期地等待它.

编辑:

要无限期地并发运行两个线程,首先创建线程,然后等待两者:

int main() {
    thread t1(Loop);
    thread t2(SecondLoop);

    t1.join();
    t2.join();
}
Run Code Online (Sandbox Code Playgroud)