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

操作系统导论

Hello World

  1. 安装gcc用来编译c代码
sudo yum install gcc
  1. 编写Hello World
#include <stdio.h>int main() {printf("Hello, World!\n");return 0;
}
  1. 使用gcc编译
    -o 是指定出处文件的名字——也就是编译完的文件会叫hello
gcc hello.c -o hello
  1. 运行
    ./hello运行

开篇

虚拟化CPU

  1. 编写一段代码,效果为反复打印用户启动程序时传入的字符串
    vim cpu.c
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
void spin(int seconds){usleep(seconds *1000000);
}
int main(int argc,char *argv[]) {if(argc!=2){fprintf(stderr,"usage:cpu<string>\n");exit(1);}char* str=argv[1];while(1){spin(1);printf("%s\n",str);}return 0;
}
  1. 编译
    gcc -o cpu cpu.c
  2. 启动一个
    ./cpu A
  3. 同时启动多个
    ./cpu A & ./cpu B & ./cpu C & ./cpu D
  4. 终止运行
    killall cpu

虚拟化内存

并发

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> // 确保包含pthread库的头文件volatile int counter = 0; // 共享计数器,使用volatile以防止编译器优化
int loops; // 每个线程要执行的循环次数// 工作线程的函数
void *worker(void *arg) {int i;for (i = 0; i < loops; i++) {counter++; // 增加共享计数器}return NULL;
}int main(int argc, char *argv[]) {if (argc != 2) { // 检查命令行参数fprintf(stderr, "usage: threads <value>\n");exit(1);}loops = atoi(argv[1]); // 从命令行参数获取循环次数pthread_t p1, p2; // 创建两个线程标识符printf("Initial value : %d\n", counter); // 打印初始计数器值// 创建两个线程pthread_create(&p1, NULL, worker, NULL); pthread_create(&p2, NULL, worker, NULL); // 等待两个线程完成pthread_join(p1, NULL); pthread_join(p2, NULL); printf("Final value : %d\n", counter); // 打印最终计数器值return 0;
}

加互斥锁

#include <pthread.h>pthread_mutex_t lock; // 声明一个互斥锁void *worker(void *arg) {int i;for (i = 0; i < loops; i++) {pthread_mutex_lock(&lock); // 加锁counter++;pthread_mutex_unlock(&lock); // 解锁}return NULL;
}int main(int argc, char *argv[]) {pthread_mutex_init(&lock, NULL); // 初始化互斥锁...pthread_mutex_destroy(&lock); // 销毁互斥锁
}

持久化


http://www.mrgr.cn/news/49336.html

相关文章:

  • wait和waitpid
  • 6 个最值得使用的 iPad 数据恢复软件
  • 第六课 Vue中的条件语句指令
  • 基于DDD架构模型优化中台架构设计的见解
  • C++从入门到起飞之——AVL树 全方位剖析!
  • C++第六讲:STL--vector的使用及模拟实现
  • C++ : STL容器之vector剖析
  • python爬虫采集某东评论
  • Java之网络编程详解
  • 【LLM KG】浅尝基于LLM的三阶段自动知识图谱构建方法
  • 机器学习【金融风险与风口评估及其应用】
  • go安装gRPC和Protobuf
  • QD1-P26、27、28 CSS 属性 文本
  • 损失函数篇 | YOLOv8更换损失函数之SlideLoss | 解决简单样本和困难样本之间的不平衡问题
  • 【Linux系统编程】第三十一弹---深入理解静态库:从零开始制作与高效使用的完全指南
  • Linux使用技巧
  • 2024 年 04 月编程语言排行榜,PHP 排名创新低?
  • java中Runnable接口是什么?基本概念、工作原理、优点、`Runnable`与`Thread`的对比、与`Callable`接口的对比、实际场景
  • Vue环境安装以及配置
  • c++速成之从string类中获取那些知识