简体   繁体   English

如何在线程中使用true?

[英]How do I use while true in threads?

Can anyone point me at the thing I try to do in this code, because SecondLoop thread is unreachable at all? 任何人都可以指出我在这段代码中尝试做的事情,因为SecondLoop线程根本无法访问? It becomes reachable only if I remove while(true) loop. 只有当我删除while(true)循环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 why I use multithreading is because I need to get two loops running at the same time. 我使用多线程的原因是因为我需要同时运行两个循环。

join blocks the current thread to wait for another thread to finish. join阻止当前线程等待另一个线程完成。 Since your t1 never finishes, your main thread waits for it indefinitely. 由于你的t1永远不会完成,你的主线程无限期地等待它。

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();
}

To run Loop and SecondLoop concurrency, you have to do something like: 要运行LoopSecondLoop并发,您必须执行以下操作:

#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. 作为join块当前线程等待其他线程完成。

.join()等待线程结束(所以在这种情况下,如果你突破while循环并退出线程函数)

使用while(true)链接到胎面运行,你应该寻找退出该循环的方法,使用某种循环控制

Based on my comment and what @Nidhoegger answered I suggest: 根据我的评论以及@Nidhoegger的回答,我建议:

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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM