给出一个使用this_thread::sleep_for的多线程示例代码
时间: 2024-04-29 16:22:35 浏览: 12
好的,下面是一个使用this_thread::sleep_for的多线程示例代码。
```
#include <iostream>
#include <thread>
#include <chrono>
void sleep_sort(int n) {
std::this_thread::sleep_for(std::chrono::milliseconds(n));
std::cout << n << " ";
}
int main() {
std::vector<int> nums = {2, 4, 1, 3, 6, 5};
std::vector<std::thread> threads;
// 启动多个线程
for (int n : nums) {
threads.push_back(std::thread(sleep_sort, n));
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
std::cout << std::endl;
return 0;
}
```
这个示例代码使用了this_thread::sleep_for函数模拟了一种简单的排序算法——睡眠排序。这个算法的原理是,通过启动多个线程,让每个线程等待一段时间后输出自己的值,这样就可以实现对一组数字进行排序。
在示例代码中,首先定义了一个sleep_sort函数,用于在线程中执行睡眠排序操作。每个线程会先睡眠一段时间,然后输出自己的值。然后,在主函数中,我们定义了一个数组nums来存放要排序的数字,然后循环遍历这个数组,为每个数字启动一个线程,将线程添加到一个线程向量threads中。最后,在主函数的末尾,我们再遍历一遍所有线程,等待它们全部执行完毕,然后输出排序后的结果。