首页 > 解决方案 > 在间隔内运行函数,同时运行主代码

问题描述

基本上我试图同时运行 2 段代码而不冻结彼此,其中之一需要一些延迟。因此,初始代码如下所示:

int main() {
    cout << "Hello World!";
    std::this_thread::sleep_for(std::chrono::milliseconds(166)); // this freezes the whole program for 166 ms
    // do other things
}

我想出了一个线程的方法:

void ThreadFunction() {
    cout << "Hello World!";
    std::this_thread::sleep_for(std::chrono::milliseconds(166));
}


int main() {
    std::thread t1(ThreadFunction);
    t1.detach();
    // do other things while also doing what the thread t1 does without waiting 166ms
}

这不完全是我的代码,但我正在尝试重新创建作为示例的代码。

线程工作正常,但我听到人们说thread.detach()不好。

那么有哪些替代方案呢?

标签: c++

解决方案


你的第二个例子似乎是你想要的。如果您不想分离线程,请不要这样做。但是,您必须join这样做,并且您只能join在某个线程完成工作时才可以使用它。

对于这个简单的例子,我建议如下(否则你需要一个条件变量或类似的信号来指示它应该停止的线程):

void ThreadFunction() {
    for (int i=0; i <100; ++i) {
        cout << "Hello World!";
        std::this_thread::sleep_for(std::chrono::milliseconds(166));
    }
}


int main() {
    std::thread t1(ThreadFunction);

    // do other things while also doing what the thread t1 does without waiting 166ms

    t1.join(); // blocks until ThreadFunction returns
}

推荐阅读