1. 程式人生 > >HOW TO SLEEP FOR IN C++

HOW TO SLEEP FOR IN C++

在使用C++11的時候,我需要對執行緒進行等待操作,下面有四種方法: 

  1. Use usleep (POSIX)
  2. Use Sleep (Windows)
  3. Use Boost.Thread
  4. Use std::this_thread::sleep_for (C++11)

Method 1: Use usleep (POSIX)

1

2

3

4

5

6

#include <unistd.h>

int main()

{

usleep(500);

}

Method 2: Use Sleep
 (Windows)

1

2

3

4

5

6

#include <Windows.h>

int main()

{

Sleep(500);

}

Method 3: Use Boost.Thread

1

2

3

4

5

#include <boost/thread/thread.hpp>

int main()

{

boost::this_thread::sleep(boost::posix_time::milliseconds(500));

}

Method 4: Use std::this_thread::sleep_for (C++11)

1

2

3

4

5

6

7

#include <chrono>

#include <thread>

int main()

{

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

}

參考文章: