简体   繁体   English

在不同的线程中停止无限循环

[英]Stop infinite loop in different thread

In my application I am using multiple threads for some time consuming task, that is intended to run for the whole duration f the application. 在我的应用程序中,我使用多个线程执行一些耗时的任务,这是为了在应用程序的整个持续时间内运行。 What I am trying to achieve is some nice and clean approach to kill the loop in second thread just before exiting app, so I can clean after loop and then close everything. 我想要实现的是一些漂亮而干净的方法在退出app之前杀死第二个线程中的循环,所以我可以在循环后清理然后关闭所有内容。

So far I've come up with this approach, but to be honest I am not huge fan of it: 到目前为止,我已经提出了这种方法,但说实话,我并不是它的忠实粉丝:

#include <iostream>
#include <thread>

bool stop_flag;

void foo()
{
    while(!stop_flag)
    {
        //do something
    }
    clean_after();
}

int main()
{
    stop_flag = false;
    std::thread whileThread(foo);

    // app lifetime

    stop_flag = true;   
    whileThread.join();
    return 0;
}

只需略微更改,您的代码就可以了:

std::atomic<bool> stop_flag;

reading and writing to the same un-synchronized variable from multiple thread is anyway undefined behavior. 从多个线程读取和写入相同的非同步变量无论如何都是未定义的行为。 Fan or not, the compiler may just optimize the check away and the loop may never start or never end. 风扇与否,编译器可能只是优化检查,循环可能永远不会启动或永远不会结束。

as answered before, you can use std::atomic_bool . 如前所述,您可以使用std::atomic_bool I'm not a fan of doing it globally - pass it to foo as its "cancellation token". 我不是全球范围内的粉丝 - 将它作为“取消令牌”传递给foo

void foo(std::atomic_bool& cancellation_token)
{
    while(!cancellationToken)
    {
        //do something
    }
    clean_after();
}

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

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