21xrx.com
2024-05-19 12:09:27 Sunday
登录
文章检索 我的文章 写文章
C++如何停止线程
2023-06-22 02:31:38 深夜i     --     --
C++ 停止 线程 方法 实现

C++是一种非常流行的编程语言,它在编写各种类型的应用程序中都非常常用。当我们在编写多线程的应用程序时,有时需要停止某些线程。本文将介绍在C++中如何停止线程。

在C++中,停止线程的最常用方法是使用std::thread::join()和std::thread::detach()方法。这两个方法用于处理线程退出的问题。

std::thread::join()方法将等待线程执行完成后才返回。在执行join()方法时,当前线程会被阻塞,直到目标线程执行完成。这意味着如果我们需要停止线程,我们可以在主线程中执行join()方法来等待该线程完成。

下面是一个简单的示例代码,演示如何使用join()方法停止线程。


#include <iostream>

#include <thread>

using namespace std;

void worker_thread()

{

  // do some work

  cout << "Worker thread started" << endl;

  // simulate some work

  std::this_thread::sleep_for(std::chrono::milliseconds(5000));

  cout << "Worker thread finished" << endl;

}

int main()

{

  cout << "Main thread started" << endl;

  // start worker thread

  std::thread t(worker_thread);

  // wait for worker thread to finish

  t.join();

  cout << "Main thread finished" << endl;

}

在上面的例子中,我们启动了一个worker_thread工作线程,并调用join()方法等待该线程完成。如果我们需要停止该线程,只需将t.join()方法移动到某个条件语句中即可。一旦该条件为真,线程将被停止。

另一种方法是使用std::thread::detach()方法,它用于将当前线程分离,使其可以运行独立于主线程。这意味着在调用detach()方法之后,主线程和分离线程将独立运行,不再互相影响。

下面是一个使用detach()方法的示例代码。


#include <iostream>

#include <thread>

using namespace std;

void worker_thread()

{

  // do some work

  cout << "Worker thread started" << endl;

  // simulate some work

  while (true)

  {

    cout << "Worker thread working..." << endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

  }

}

int main()

{

  cout << "Main thread started" << endl;

  // start worker thread

  std::thread t(worker_thread);

  // detach worker thread

  t.detach();

  cout << "Main thread finished" << endl;

}

在上面的例子中,我们启动了一个工作线程,并将其分离使用detach()方法。该线程将独立于主线程运行,因此我们没有办法像使用join()方法那样停止它。

总之,与大多数编程语言一样,在C++中停止线程并不是一件容易的事情。但是使用join()和detach()方法,我们可以在必要时停止线程或将其分离。当编写多线程的应用程序时,这是应该学会的基本技能。

  
  

评论区

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