21xrx.com
2025-03-26 02:02:21 Wednesday
文章检索 我的文章 写文章
C++ 主线程等待子线程结束的实现方法
2023-07-05 19:41:14 深夜i     153     0
C++ 主线程 子线程 等待 实现方法

C++ 是一种多线程编程语言,它可以同时执行多个线程。但是,主线程可能需要等待子线程完成后再继续执行其他操作。这就需要一种方法来实现主线程等待子线程结束,下面我们来介绍一些常用的方法。

方法一:join() 函数

join() 函数是用来等待子线程结束的。使用该函数可以让主线程等待子线程结束并返回子线程的返回值(如果有的话)。

示例代码:

#include <iostream>
#include <thread>
using namespace std;
void thread_func()
  cout << "This is a child thread." << endl;
int main()
{
  thread t(thread_func);
  cout << "This is a main thread." << endl;
  t.join();
  cout << "Child thread is joined with main thread." << endl;
  return 0;
}

在上面的示例代码中,首先定义了一个子线程 t,然后通过 join() 函数来等待子线程结束。在 join() 函数之后的语句会等待子线程执行完毕后才会被执行。

方法二:detach() 函数

detach() 函数用于将子线程和主线程分离。使用该函数可以让主线程不关心子线程的状态,子线程在执行完后会自动释放它的资源。

示例代码:

#include <iostream>
#include <thread>
using namespace std;
void thread_func()
  cout << "This is a child thread." << endl;
int main()
{
  thread t(thread_func);
  cout << "This is a main thread." << endl;
  t.detach();
  cout << "Child thread is detached from main thread." << endl;
  return 0;
}

在上面的示例代码中,使用 detach() 函数分离了子线程 t,主线程不再等待它执行完毕。在 detach() 函数之后的语句会立即被执行。

方法三:条件变量和互斥量

条件变量和互斥量是实现线程同步的重要手段,它们也可以用于实现主线程等待子线程结束的功能。

示例代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
bool ready = false;
mutex mtx;
condition_variable cv;
void thread_func()
{
  cout << "This is a child thread." << endl;
  ready = true;
  cv.notify_one(); // 通知条件变量
}
int main()
{
  thread t(thread_func);
  unique_lock<mutex> lock(mtx);
  while (!ready) // 如果条件不满足
  {
    cv.wait(lock); // 等待条件变量
  }
  cout << "Child thread is finished." << endl;
  t.join();
  cout << "Child thread is joined with main thread." << endl;
  return 0;
}

在上面的示例代码中,首先定义了一个子线程 t,在子线程中设置了一个标志位 ready,表示子线程已经执行完毕。然后,在主线程中使用互斥量和条件变量来等待子线程完成。在条件变量的 wait() 函数中,当条件不满足时会自动释放互斥量,等待满足条件后再重新获取互斥量继续执行。在子线程中使用 notify_one() 函数通知条件变量,当条件满足时主线程才会继续执行。最后使用 join() 函数等待子线程结束。

总结

以上就是实现主线程等待子线程结束的三种方法。其中,join() 函数比较简单明了,detach() 函数适用于一些需要长时间运行的子线程,条件变量和互斥量则是实现线程同步的重要手段。在实际应用中,可以根据具体需求选择合适的方法来实现主线程等待子线程结束。

  
  

评论区