21xrx.com
2025-03-27 00:31:36 Thursday
文章检索 我的文章 写文章
C++如何暂停线程?
2023-07-05 13:21:05 深夜i     --     --
C++ 暂停 线程

C++是一种流行的编程语言,常用于开发复杂的应用程序和系统。线程是C++中经常使用的一个重要概念,它使得程序可以同时执行多个任务,提高了程序的并发性和性能。但有时候需要暂停线程来完成一些特定的操作或任务,本文将介绍如何在C++中暂停线程。

在C++中,要暂停线程,有几种方法可以实现。其中最简单的方法是使用sleep函数。这个函数接受一个整数参数,表示暂停的毫秒数。例如,以下代码将暂停线程1000毫秒:

#include <iostream>
#include <chrono>
#include <thread>
int main() {
  std::cout << "Hello World!" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  std::cout << "Goodbye World!" << std::endl;
  return 0;
}

这个代码创建了一个线程并暂停了1秒钟,然后输出一条消息。

另一种方法是使用互斥锁。互斥锁是一种保护共享资源的方式,在多个线程之间同步共享资源。要暂停线程,可以使用互斥锁阻止多个线程同时访问共享资源。例如,以下代码演示了如何使用互斥锁暂停线程:

#include <iostream>
#include <thread>
#include <mutex>
std::mutex g_mutex;
bool g_stop = false;
void do_work() {
  while (!g_stop) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::lock_guard<std::mutex> lock(g_mutex);
    std::cout << "Working..." << std::endl;
  }
}
int main() {
  std::thread t(do_work);
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  {
    std::lock_guard<std::mutex> lock(g_mutex);
    g_stop = true;
  }
  t.join();
  std::cout << "Done!" << std::endl;
  return 0;
}

在这个例子中,do_work函数不断地运行,直到g_stop为true。g_stop是一个全局变量,其初始值为false。在main函数中,线程首先启动do_work函数,然后等待1秒钟,以便让线程有一些时间来工作。线程然后获取互斥锁(使用std::lock_guard)并将g_stop设置为true,因此do_work函数退出并结束线程。

总结:

暂停线程在C++中是一件容易的事情。可以使用简单的sleep函数,也可以使用互斥锁来阻止其他线程访问共享资源。无论使用哪种方法,暂停线程都是一种非常常见的技术,可以帮助程序员实现更高效和可靠的代码。

  
  

评论区