21xrx.com
2024-09-20 05:33:03 Friday
登录
文章检索 我的文章 写文章
C++ 如何判断线程执行完毕?
2023-06-28 04:33:02 深夜i     --     --
C++ 线程 执行完毕 判断

在编写多线程程序时,经常需要等待某个线程执行完毕后才能继续执行下面的代码。C++提供了一些方法来判断一个线程是否执行完毕。

1. join()方法

join()方法是最常用的等待线程执行完毕的方法。调用join()方法会阻塞当前线程,直到被调用的线程执行完毕。例如:


#include <iostream>

#include <thread>

void func()

  // do something

int main()

{

  std::thread t(func);

  t.join(); // 等待线程t执行完毕再继续执行下面的代码

  std::cout << "Thread t has finished." << std::endl;

  return 0;

}

2. detach()方法

如果不想等待某个线程执行完毕,可以使用detach()方法将该线程分离,使其在后台执行。此时无法再通过join()方法等待该线程执行完毕。例如:


#include <iostream>

#include <thread>

void func()

  // do something

int main()

{

  std::thread t(func);

  t.detach(); // 将线程t分离,使其在后台执行

  std::cout << "Thread t has been detached." << std::endl;

  return 0;

}

3. std::future和std::promise

std::future和std::promise是一种较为灵活的方式,可以在主线程中等待另一个线程执行完毕并获取其返回值。例如:


#include <iostream>

#include <thread>

#include <future>

int func(int x)

{

  // do something

  return x * x;

}

int main()

{

  std::promise<int> p;

  std::future<int> f = p.get_future();

  std::thread t([&p](){

    int result = func(10);

    p.set_value(result);

  });

  int result = f.get(); // 等待线程t执行完毕并获取其返回值

  std::cout << "Result: " << result << std::endl;

  t.join(); // 等待线程t执行完毕

  return 0;

}

以上是C++中判断线程是否执行完毕的几种方法,实际使用中需要根据具体情况选择合适的方式。请注意避免线程竞态和死锁等问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复