#include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> int shared_var = 0; void * thread( void * arg ) { while (1) { printf( "in the thread shared_var:%d\n" , --shared_var); } } int main() { pthread_t pt; int ret = pthread_create(&pt, NULL, ( void *)thread, NULL); if (ret != 0) printf( "fail to create thread\n" ); while (1) { printf( "in the main shared_var:%d\n" , ++shared_var); } pthread_join(pt, NULL); return 0 ; }对该代码的每一行代码都写上注释
时间: 2024-01-01 22:05:41 浏览: 52
```
#include <sys/types.h> // 包含系统类型定义的头文件
#include <stdio.h> // 标准输入输出头文件
#include <unistd.h> // 包含POSIX操作系统API的头文件
#include <pthread.h> // 多线程编程头文件
int shared_var = 0; // 定义一个全局变量 shared_var 并初始化为 0
void * thread( void * arg ) { // 定义一个线程函数,参数为 void * 类型的指针
while (1) { // 线程执行循环
printf( "in the thread shared_var:%d\n" , --shared_var); // 打印线程执行结果,每次将 shared_var 自减 1
}
}
int main() { // 主函数入口
pthread_t pt; // 定义一个线程 ID
int ret = pthread_create(&pt, NULL, ( void *)thread, NULL); // 创建一个线程,将线程 ID 存储在 pt 中,执行 thread 函数,并传递 NULL 参数
if (ret != 0) printf( "fail to create thread\n" ); // 如果创建线程失败则输出错误信息
while (1) { // 主函数执行循环
printf( "in the main shared_var:%d\n" , ++shared_var); // 打印主函数执行结果,每次将 shared_var 自加 1
}
pthread_join(pt, NULL); // 等待线程执行完毕
return 0 ; // 主函数返回值为 0
}
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)