我如何在线程中使用true? [英] How do I use while true in threads?

查看:49
本文介绍了我如何在线程中使用true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以指出我在这段代码中尝试执行的操作,因为SecondLoop线程根本无法访问吗?只有删除while(true)循环,它才可以访问.

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.

推荐答案

join 阻止当前线程等待另一个线程完成.由于您的t1从未完成,因此您的主线程将无限期地等待它.

join blocks the current thread to wait for another thread to finish. Since your t1 never finishes, your main thread waits for it indefinitely.

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

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

这篇关于我如何在线程中使用true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆