请用C++语言给出一段示例代码,演示多线程可以同时运行不同的代码块
时间: 2024-06-04 16:12:47 浏览: 23
好的,以下是一段示例代码,演示多线程可以同时运行不同的代码块:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *task1(void *arg) {
for (int i = 1; i <= 10; i++) {
printf("Task 1: %d\n", i);
sleep(1);
}
pthread_exit(NULL);
}
void *task2(void *arg) {
for (int i = 1; i <= 10; i++) {
printf("Task 2: %d\n", i);
sleep(1);
}
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, task1, NULL);
pthread_create(&tid2, NULL, task2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
在这个示例代码中,我们定义了两个函数task1和task2,它们分别打印1到10的数字,每个数字之间暂停1秒钟。我们使用pthread库创建了两个线程,分别运行task1和task2函数。
在主函数中,我们使用pthread_join函数,等待两个线程都结束后再退出程序。这样,我们就演示了多线程可以同时运行不同的代码块。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)