21xrx.com
2025-04-12 09:25:26 Saturday
文章检索 我的文章 写文章
C++中判断线程是否结束的方法
2023-06-27 05:28:51 深夜i     138     0
C++ 线程 判断 结束 方法

在C++中,线程是一种非常常用的并发机制。在多线程编程中,我们通常需要知道线程是否已经结束。这里介绍一些在C++中判断线程是否结束的方法。

方法1:使用std::thread::joinable()方法

std::thread类中的joinable()方法可以用于判断线程是否已经运行结束。如果返回值为true,则表示线程正在运行,否则就是已经结束了。

示例代码:

#include <iostream>
#include <thread>
using namespace std;
void foo()
  cout << "Hello
int main() {
  thread t(foo);
  if (t.joinable())
    cout << "Thread is running..." << endl;
   else
    cout << "Thread has ended." << endl;
  
  t.join();
  return 0;
}

方法2:使用std::future和std::async函数

std::async函数可以异步执行一个函数,并返回一个std::future对象,该对象可以用于获取函数返回值,并可以判断线程是否结束。如果std::future的wait_for()方法返回std::future_status::ready,则表示函数已经结束,否则还在运行。

示例代码:

#include <iostream>
#include <future>
using namespace std;
int foo() world!" << endl;
  return 0;
int main() {
  future<int> f = async(foo);
  while (f.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
    cout << "Thread is running..." << endl;
  
  cout << "Thread has ended." << endl;
  return 0;
}

方法3:使用std::this_thread::sleep_for()方法

std::this_thread::sleep_for()方法可以用于让当前线程睡眠指定的时间。我们可以利用这个特性,在等待线程结束的时候判断线程是否还在运行。

示例代码:

#include <iostream>
#include <thread>
using namespace std;
void foo()
  cout << "Hello
int main() {
  thread t(foo);
  while (t.joinable()) {
    cout << "Thread is running..." << endl;
    this_thread::sleep_for(chrono::milliseconds(10));
  }
  cout << "Thread has ended." << endl;
  t.join();
  return 0;
}

总结

以上三种方法都可以用于判断线程是否结束,使用哪种方法可以根据实际需求来选择。在编写多线程程序时,要注意避免一些常见的并发问题。例如,要注意线程安全,避免使用共享资源等。

  
  

评论区

请求出错了