自动终止 C++11 STL 线程

Auto-terminate C++11 STL thread

本文关键字:STL 线程 C++11 终止      更新时间:2023-10-16

我希望 STL 线程在完成它应该做的事情后自行终止;另外,有没有办法知道线程何时完成?就像一个事件左右。

提前谢谢。

如果您想要一种方法来轮询线程的完成状态,而不是简单地使用 join 阻塞,您可以使用 async 生成您的线程,并通过等待 0 超时来轮询返回的future以完成:

void f() {
  std::this_thread::sleep_for(std::chrono::seconds{2});
}
int main() {
  auto const zero = std::chrono::seconds{0};
  auto result = std::async(std::launch::async, f);
  while (result.wait_for(zero) != std::future_status::ready) {
    std::cout << "I'm still waiting...n" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds{100});
  }
  result.get();
  std::cout << "Done.n";
}

线程在函数 f 结束后终止,并且:

void f()
{
    do_some_work();
    // end of function f
}
...
{
    ...
    std::thread t(f);
    do_some_other_work();
    t.join();
}

函数join ->块是你当前的线程,直到线程 t 停止。

该操作称为join: http://www.cplusplus.com/reference/thread/thread/join/

调用时,当前线程将等待另一个线程完成。就这么简单。而已。

就像斯维特洛夫娃和羽蛇神说的那样:使用连接操作来确保线程完成。

但是,如果您想知道线程何时完成,而不使用阻塞连接操作,则可以分离线程并使用一些全局变量来检查线程是否处于活动状态。伪代码:

std::atomic<bool> imdone;
void myThreadfunction() {
    //dosomestuff;
    imdone = true;
    return;
}
int main() {
    imdone = false;
    std::thread t1(myThreadfunction);
    t1.detach();
    //dosomeotherstuff
    while(!imdone) {
        //dosomeotherstuffwhilethreadisrunning
    }
}

但是,为要独立运行的每个线程使用全局变量并不是很好......