21xrx.com
2024-09-20 05:47:14 Friday
登录
文章检索 我的文章 写文章
如何在C++中暂停线程?
2023-07-02 11:26:11 深夜i     --     --
C++ 线程 暂停

在C++中,暂停线程是一种非常有用的技术。它可以让开发者在代码中间停止某些线程的执行,只有在会话被恢复后才会继续执行。这种技术可以用于减少资源的使用,实现更高效的程序。

那么在C++中,如何暂停线程呢?

C++标准中并没有提供直接的暂停线程的方法,但是我们可以通过一些技巧来实现。其中最常用的三种方法如下:

1、Sleep函数

Sleep函数可以将当前线程阻塞指定的时间,时间到后线程会继续运行。可以通过指定0ms的时间来实现线程暂停的效果。

比如:


#include <windows.h>

#include <iostream>

using namespace std;

int main() {

  cout<<"Start"<<endl;

  Sleep(1000); //暂停1000ms

  cout<<"End"<<endl;

  return 0;

}

2、Semaphore信号量

Semaphore信号量是一种操作系统提供的同步工具,它可以用来控制多个线程对共享资源的访问,以此来保证程序的正确性。在C++中,我们可以通过Semaphore控制线程的执行。

比如:


#include <iostream>

#include <thread>

#include <mutex>

#include <chrono>

#include <windows.h>

using namespace std;

class Semaphore{

  public:

    Semaphore(int count = 0)

      m_count = count;

    

    void Wait(){

      unique_lock<mutex> lock(m_mutex);

      while(m_count == 0) {

        m_cv.wait(lock);

      }

      m_count--;

    }

    void Signal(){

      unique_lock<mutex> lock(m_mutex);

      m_count++;

      m_cv.notify_one();

    }

  private:

    int m_count;

    mutex m_mutex;

    condition_variable m_cv;

};

Semaphore sem(0);

void ThreadFunction(){

  cout << "Thread start." << endl;

  sem.Wait(); //线程等待

  cout << "Thread end." << endl;

}

int main(){

  cout << "Main start." << endl;

  thread t(ThreadFunction);

  this_thread::sleep_for(chrono::milliseconds(2000)); //暂停2s

  sem.Signal(); //释放线程

  cout << "Main end." << endl;

  t.join();

  return 0;

}

3、使用多线程库

C++的多线程库中提供了非常方便的线程控制函数,包括std::this_thread::sleep_for()和std::this_thread::yield()等。这些函数可以在任何地方暂停线程的执行,并且可以设置暂停的时间。

比如:


#include <iostream>

#include <thread>

#include <chrono>

using namespace std;

int main(){

  cout<<"Start"<<endl;

  this_thread::sleep_for(chrono::seconds(1)); //暂停1s

  cout<<"End"<<endl;

  return 0;

}

总结

以上是三种在C++中实现线程暂停的方法,具体使用哪一种方法取决于开发者对程序的需求和背景。无论使用哪种方法,都需要注意线程安全和线程调度的问题,确保程序的正确性和高效性。

  
  

评论区

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