当前位置: 首页 > news >正文

多线程编程简单例题(3个线程) Linux环境 C语言实现

问题:编写程序完成如下功能:程序创建2个线程,然后:
        1> 主线程先打印“I am main thread”,然后睡眠2秒后,打印"main thread wake up",主线程退出
        2> 第一个新线程先打印“I am the first new thread”,然后睡眠3秒后,打印"the first new thread wake up",退出
        3> 第二个新线程先打印“I am the second new thread”,然后睡眠5秒后,打印"the fsecond new thread wake up",退出
    要求能看到所有打印信息



代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>void *fun1(){printf("I am the first new thread\n");sleep(3);printf("the first new thread wake up\n");return NULL;
}void *fun2(){printf("I am the second new thread\n");sleep(5);printf("the second new thread wake up\n");return NULL;
}int main(int argc,char *argv[]){pthread_t id[2];int ret = 0;ret = pthread_create(&id[0],NULL,fun1,NULL); // thread1ret += pthread_create(&id[1],NULL,fun2,NULL); // thread2if(ret){printf("pthread_create failed\n");return 1;}printf("I am main thread\n"); // main threadsleep(2);printf("main thread wake up\n");pthread_exit(NULL); // main thread exitpthread_join(id[0],NULL); // thread1 exitpthread_join(id[1],NULL); // thread2 exitreturn 0;
}

输出:

http://www.lryc.cn/news/465247.html

相关文章:

  • UG NX12.0建模入门笔记:1.2 鼠标的基本操作
  • NVME盘未格式化导致Ubuntu20.04启动慢
  • VSCode创建插件HelloWorld找不到指令解决办法
  • 第20场 小白入门赛本场比赛为「蓝桥·算法双周赛」第二十场分级赛——小白入门赛
  • 论文研读 | End-to-End Object Detection with Transformers
  • 构建高效在线教育平台:Spring Boot的力量
  • C#Process进程的使用,以及对ProcessInfo中所有的参数详细记录
  • STM32中的RAM和ROM分别是什么
  • Spring--1
  • 【Flutter】页面布局:流式布局(Wrap、Flow)
  • Delphi数据字典TDictionary
  • VsCode 如何自定义代码片段(Code Snippet)
  • Linux服务器前后端项目部署vue+springboot—搭建服务器上的运行环境(JDK、Redis、MySQL、Nginx)
  • 随记:有关idea中jdk版本
  • 【算法篇】贪心类(1)(笔记)
  • el-select 可搜索、多选状态遮挡住搜索框
  • el-table中实现可选表格区域的鼠标事件检测
  • 特种作业操作登高架设作业历年真题附答案
  • schedule-执行周期性任务
  • python图片文件路径排序
  • ARTTrack6/M、ARTTrack5、ART AT7-80横向对比
  • 【Vue】Vue3.0(十三)中标签属性ref(加在普通标签上、加在组件标签上)、局部样式
  • Linux系统基础-文件系统
  • 机器学习和深度学习常用的工具库
  • 【unity小技巧】Unity6 LTS版本安装和一些修改和新功能使用介绍
  • 5种边界填充
  • 鸿蒙网络编程系列7-TLS安全数据传输单向认证示例
  • LangGraph 源码分析 | BaseTool 模板类
  • vulnhub靶场之JOY
  • intel和AMD突然联姻,这操作给我看傻了