c++ 线程怎么定时执行
时间: 2023-08-05 20:23:27 浏览: 60
在C++中,可以使用std::thread和std::chrono库来实现线程的定时执行。
具体实现步骤如下:
1. 创建一个线程,用来执行需要定时执行的操作。
2. 在线程中使用std::this_thread::sleep_for()函数来使线程休眠一段时间,等待下一次执行。
以下是一个简单的例子,程序每隔1秒钟会输出一次"Hello, world!":
```c++
#include <iostream>
#include <chrono>
#include <thread>
void myThreadFunction()
{
while (true)
{
std::cout << "Hello, world!" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread myThread(myThreadFunction);
myThread.join();
return 0;
}
```
在上面的代码中,myThreadFunction()函数是一个线程函数,它会不断地输出"Hello, world!",然后休眠1秒钟,等待下一次执行。在main()函数中,我们创建了一个线程myThread,并将myThreadFunction()函数作为线程函数传递进去。然后,我们调用myThread.join()函数,等待线程执行完毕。
需要注意的是,std::this_thread::sleep_for()函数可以接受各种时间单位,包括std::chrono::milliseconds、std::chrono::microseconds等等。如果需要更高的时间精度,可以使用更小的时间单位。