线程1把1,2,3,…,10打印在屏幕上(每隔4秒钟打印一个);另一个线程2把11,12,…,20打印在屏幕上(每隔2秒钟打印一个)(编译时要添加-lpthread参数)
时间: 2023-12-05 10:04:01 浏览: 15
以下是使用C++11中的线程库实现该功能的示例代码:
```c++
#include <iostream>
#include <thread>
using namespace std;
void print1to10() {
for(int i = 1; i <= 10; i++) {
cout << i << endl;
this_thread::sleep_for(chrono::seconds(4)); // 暂停4秒
}
}
void print11to20() {
for(int i = 11; i <= 20; i++) {
cout << i << endl;
this_thread::sleep_for(chrono::seconds(2)); // 暂停2秒
}
}
int main() {
thread t1(print1to10);
thread t2(print11to20);
t1.join();
t2.join();
return 0;
}
```
在上述代码中,我们定义了两个函数`print1to10`和`print11to20`,分别用于打印1到10和11到20。每个函数都包含一个循环,打印数字并使用`this_thread::sleep_for`函数暂停一段时间。
在`main`函数中,我们创建两个线程`t1`和`t2`,分别调用`print1to10`和`print11to20`函数。然后我们使用`join`函数等待两个线程完成。
需要注意的是,在编译时需要添加`-lpthread`参数,以便链接线程库。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)