基于POSIX标准库的读者-写者问题的简单实现

文章目录

  • 实验要求
  • 分析
    • 保证读写、写写互斥
    • 保证多个读者同时进行读操作
  • 读者优先
    • 实例代码
    • 分析
  • 写者优先
    • 示例代码
    • 分析

实验要求

  1. 创建一个控制台进程,此进程包含n个线程。用这n个线程来表示n个读者或写者。
  2. 每个线程按相应测试数据文件的要求进行读写操作。
  3. 信号量机制分别实现读者优先写者优先的读者-写者问题。

分析


由于只有一个共享文件, 而有n个读线程, n个写者线程需要互斥地对该文件进行读写操作

读者写者问题需要保证

  • 读读不互斥、允许多个读者同时进行读操作
  • 读写、写写互斥

保证读写、写写互斥


由于临界资源(共享文件)只有一个, 所以创建一个互斥信号量(资源数量只有1份)mutex_file来对进行对文件地互斥操作

保证多个读者同时进行读操作


由于需要保证多个读者不互斥地对文件进行读操作, 所以设置一个进程内的全局变量(线程共享) reading_count, 表示正在对文件进行读操作的线程的数量.

每当有一个读线程进入临界区后, 对该变量的数值+1.

由于有多个读线程, 所以对该全局变量的访问也需要互斥, 因此增加一个互斥信号量mutex_count

如果读线程判断到reading_count != 0, 则不用对信号量mutex_fileP操作, 可以直接进入临界区. 否则, 即该读线程是第一个读线程, 该读线程首先要对信号量mutex_file做P操作.

读者优先

  • 主函数

    • 打开要互斥访问的文件
    • 初始化信号量
    • 创建N个读者线程, N个写者线程mutex_file信号量代表的
  • 读者线程

    • 不断地请求对文件的操作(对信号量mutex_file进行P操作).
    • 打印读者线程id, 用于后续分析.
    • 如果成功的进入临界区, 读取文件的大小, 并打印到标准输出.
  • 写者线程

    • 不断地请求对文件的操作(对信号量mutex_file进行P操作).
    • 打印写者线程id, 用于后续分析.
    • 如果成功的进入临界区, 则对文件写一行文本, 这里为hello world\n.

实例代码

#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/file.h>
#include <pthread.h>
#include <semaphore.h>
// convient to code
#define P(x) sem_wait(x);
#define V(x) sem_post(x);
sem_t mutex_count;
sem_t mutex_file;
sem_t mutex_print; // make the print info correct
int reading_count = 0; // the amount of the reading thread
int fd; // the shared file descriptor
const int N = 5;// the thread of the writer
char writer_str[] = "hello world\n";
void* writer_thread(void* arg) {while (true) {// try to operate the fileP(&mutex_file);P(&mutex_print);printf("the writer %d is writing\n", arg);fflush(stdout);V(&mutex_print);// write into the filewrite(fd, writer_str, sizeof(writer_str) - 1);sleep(1);// release the fileV(&mutex_file);}
}
// the thread of the reader
void* reader_thread(void* arg) {while (true) {// Firstly, we need to check and plus the reading_count// so, we try to catch the mutex_countP(&mutex_count);// if the reader is the first reader// if mutex_file = 0, if (reading_count == 0) {P(&mutex_file);}reading_count++;V(&mutex_count);P(&mutex_print);printf("the reader %d is reading  #", arg);char buf[1024];// move file pointer to left 0, to read all content of filelseek(fd, 0, SEEK_SET);int len = read(fd, buf, sizeof(buf));printf("len = %d\n", len);fflush(stdout);// printf("str = \n%.*s\n", len, buf);// fflush(stdout);sleep(1);V(&mutex_print);// after reading, the reader leave, count--P(&mutex_count);reading_count--;// if the reader is the last readerif (reading_count == 0) {V(&mutex_file);}V(&mutex_count);}
}
int main(int argc, char const *argv[]) {// if use the cmd// if (argc < 2) {//     printf("usage : %s <n>\n", argv[0]);//     exit(1);// } // int N = atoi(argv[1]);// open a file "data.txt", which can written and read,// if not exists, crate it, if already have sth, clear it.fd = open("data.txt", O_RDWR | O_CREAT | O_TRUNC);if (fd == -1) {char msg[] = "error to open the file\n";write(2, msg, sizeof(msg) - 1);return 1;}printf("file descriptor = %d\n", fd);/*** initialize the semaphores*  arg1 : the semaphore*  arg2: 0 means share in processes*  arg3: 1 means initial value of the semaphore, there 1 means mutual-sema*/sem_init(&mutex_count, 0, 1); sem_init(&mutex_file, 0, 1); sem_init(&mutex_print, 0, 1); /*** initialize the threads*/std::vector<pthread_t> writer(N), reader(N);// create N writer thread, N reader threadfor (int i = 0; i < N; i++) {pthread_create(&writer[i], nullptr, writer_thread, (void*) i + 1);pthread_create(&reader[i], nullptr, reader_thread, (void*) (N + i + 1));}// main thread waiting 2*N threadsfor (int i = 0; i < N; i++) {pthread_join(writer[i], nullptr);pthread_join(writer[i], nullptr);}// destory semaphoressem_destroy(&mutex_count);sem_destroy(&mutex_file);sem_destroy(&mutex_print);return 0;
}

分析

假设读写线程都有N = 5个, 如果尝试运行一下该程序
在这里插入图片描述
由于第一个创建的线程是写线程, 所以writer1会对文件进行写操作
后续当第一个读线程获取到文件的操作权后, 此时后续的读写线程都已经就绪, 因为此时reading_count=1, 所以其余读线程不会执行对信号量mutex_fileP操作, 而直接进入临界区, 但是写线程执行了对信号量mutex_fileP操作, 从而被阻塞, 加如到了该信号量的阻塞队列中. 接着, 其余读线程也顺势进入临界区, 并且由于一个线程内是持续(while(true))对共享文件做P操作的, 所以一个读线程完成读操作后会立即再次对文件发起读请求. 从而使得可能在后续读线程就绪前, 就准备好的写线程一直被阻塞. 从而引起了这些写线程出现饥饿现象.
读者优先时产生写线程饥饿

当然, 如果线程中不加入死循环, 则每个线程只对文件操作一次, 则所有的线程都有机会操作文件.此时写线程只会饥饿, 但不至于饿死. 而加入死循环, 可能会导致线程饿死.

写者优先


这里的写者优先并不是写者的优先级高于读者, 更不会导致读者出现饥饿情况.
实际上, 这里的读者和写者的优先级是一样的

前面读者优先的实现问题在于: 当读线程在占用文件时, 其它读线程直接进入临界区, 则不被阻塞, 仅有后续的写线程被阻塞

一种解决办法就是设置一个信号量让两类线程都可以因为请求文件被阻塞, 但是同时保证读-读不被阻塞

我们在原先的读者优先的实现中, 在最外层增加一个互斥信号量mutex_equal

为了保证会因请求文件而阻塞, 所以在对mutex_file进行P操作之前, 对mutex_equal执行P操作

由于要保证多个读者同时读取文件, 则当读者进入临界区后, 对mutex_wprivilege进行V操作

表示可以获得写者优先的线程数. 初始值为1表示当前读线程谦让最多1个写线程执行

在写线程执行时, 先对mutex_equal进行P操作, 如果此时mutex_equal= 1, 表示该写线程是第一个就绪且请求写文件的写线程, 则继续对mutex_file信号量进行P操作. 如果mutex_equal= 0, 表明该写线程不是第一个请求文件而被阻塞的写线程, 不应该享有让读线程谦让的资格. 此时被mutex_equal阻塞.

在读线程执行时, 先对mutex_wprivilege进行P操作, 如果被阻塞, 则说明此时有写线程正在请求文件(即被信号量mutex_file阻塞), 此时读线程被信号量mutex_wprivilege阻塞

示例代码

#include <iostream>
#include <vector>
#include <sys/file.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
sem_t mutex_count;
sem_t mutex_print;
sem_t mutex_file;
sem_t mutex_equal;
int reading_count = 0;
int fd;
const int N = 5;
#define P(x) sem_wait(x);
#define V(x) sem_post(x);
/*** P -> sem_wait -1* V -> sem_post +1
*/
// the thread of the writer
char writer_str[] = "hello world\n";
void* writer_thread(void* arg) {while (true) {// the first thread try to catch the file P(&mutex_equal);P(&mutex_file);P(&mutex_print);printf("the writer %d is writing\n", arg);fflush(stdout);V(&mutex_print);write(fd, writer_str, sizeof(writer_str) - 1);sleep(1);V(&mutex_file);// the first blocking-thread of mutex_file leave the critical zoneV(&mutex_equal);}
}
// the thread of the reader
void* reader_thread(void* arg) {while (true) {// check if the first thread of blocked-queue of mutex_file is the writer// if there is writer blocking, the write can't go into critcal zone P(&mutex_equal);P(&mutex_count);// if the reader is the first readerif (reading_count == 0) {P(&mutex_file);}reading_count++;// read_count++;// printf("%d %d\n", write_count, read_count);V(&mutex_count);P(&mutex_print);printf("the reader %d is reading  #", arg);char buf[1024];// move file pointer to left 0 lseek(fd, 0, SEEK_SET);int len = read(fd, buf, sizeof(buf));printf("len = %d\n", len);fflush(stdout);// fflush(stdout);// printf("str = \n%.*s\n", len, buf);sleep(1);V(&mutex_print);V(&mutex_equal);// after reading, the reader leave, count--P(&mutex_count);reading_count--;// if the reader is the last readerif (reading_count == 0) {V(&mutex_file);}V(&mutex_count);}    
}
int main(int argc, char const *argv[]) {// if (argc < 2) {//     printf("usage : %s <n>\n", argv[0]);//     exit(1);// } // int N = atoi(argv[1]);fd = open("data.txt", O_RDWR | O_CREAT | O_TRUNC);/*** initialize the semaphores*  arg1 : the semaphore*  arg2: 0 means share in processes*  arg3: 1 means initial value of the semaphore*/sem_init(&mutex_count, 0, 1); sem_init(&mutex_file, 0, 1); sem_init(&mutex_print, 0, 1); sem_init(&mutex_equal, 0, 1); /*** initialize the threads* */printf("file descriptor = %d\n", fd);vector<pthread_t> writer(N), reader(N);for (int i = 0; i < N; i++) {pthread_create(&writer[i], nullptr, writer_thread, (void*) i + 1);pthread_create(&reader[i], nullptr, reader_thread, (void*) (N + i + 1));}// main thread waiting 2*N threadsfor (int i = 0; i < N; i++) {pthread_join(writer[i], nullptr);pthread_join(writer[i], nullptr);}// destory semaphoressem_destroy(&mutex_count);sem_destroy(&mutex_file);sem_destroy(&mutex_print);sem_destroy(&mutex_equal);return 0;
}

分析

修改后的程序的输出结果: 读者和写者较为平均的访问了文件.
在这里插入图片描述
对于mutex_equal的阻塞队列的队首.

  • mutex_file的阻塞队列为空(这种情况下mutex_equal= 1), 此时mutex_equal的阻塞队列队首的读者线程, 会直接进入临界区.
  • mutex_file的阻塞队列有一个写者线程时, 此时mutex_equal的阻塞队列队首的读/写线程都不会进入mutex_file的阻塞队列.

很明显, mutex_file的阻塞队列最多只会有一个线程(只可能是写线程)
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/3015204.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

AI模型:windows本地运行下载安装ollama运行Google CodeGemma【自留记录】

AI模型&#xff1a;windows本地运行下载安装ollama运行Google CodeGemma【自留记录】 1、下载&#xff1a; 官网下载&#xff1a;https://ollama.com/download&#xff0c;很慢&#xff0c;原因不解释。 阿里云盘下载&#xff1a;https://www.alipan.com/s/jiwVVjc7eYb 提取码…

工业级POE交换机的POE供电功能有哪些好处

工业级POE交换机的POE供电功能是一种高效、方便、安全的供电方式。POE技术能够通过Ethernet网线传输电力和数据&#xff0c;无需额外的电源线路&#xff0c;从而简化了设备的安装和布线工作。在工业环境中&#xff0c;特别是一些远距离、高墙壁或者天花板安装位置不便的地方&am…

聚苯胺纳米纤维膜的制备过程

聚苯胺纳米纤维膜是一种由聚苯胺&#xff08;PANI&#xff09;纳米纤维构成的薄膜材料。聚苯胺是一种具有优良导电性、氧化还原性和化学稳定性的高分子材料&#xff0c;因此聚苯胺纳米纤维膜也具备这些特性&#xff0c;并展现出广阔的应用前景。 在制备聚苯胺纳米纤维膜时&…

RLC防孤岛负载测试的案例和实际应用经验有哪些?

RLC防孤岛负载测试是用于检测并防止电力系统出现孤岛现象的测试方法&#xff0c;孤岛现象是指当电网因故障或停电而与主电网断开连接时&#xff0c;一部分电网仍然与主电网保持连接&#xff0c;形成一个孤立的电网。这种情况下&#xff0c;如果电力系统不能及时检测到孤岛并采取…

Pascal Content数据集

如果您想使用Pascal Context数据集&#xff0c;请安装Detail&#xff0c;然后运行以下命令将注释转换为正确的格式。 1.安装Detail 进入项目终端 #即 这是在我自己的项目下直接进行克隆操作&#xff1a; git clone https://github.com/zhanghang1989/detail-api.git $PASCAL…

一、vue3专栏项目 -- 1、项目介绍以及准备工作

这是vue3TS的项目&#xff0c;是一个类似知乎的网站&#xff0c;可以展示专栏和文章的详情&#xff0c;可以登录、注册用户&#xff0c;可以创建、删除、修改文章&#xff0c;可以上传图片等等。 这个项目全部采用Composition API 编写&#xff0c;并且使用了TypeScript&#…

4G工业路由器快递柜应用案例(覆盖所有场景)

快递柜展示图 随着电商的蓬勃发展,快递行业迎来高速增长。为提高快递效率、保障快件安全,智能快递柜应运而生。但由于快递柜部署环境复杂多样,网络接入成为一大难题。传统有线宽带难以覆盖所有场景,而公用WiFi不稳定且存在安全隐患。 星创易联科技有限公司针对这一痛点,推出了…

视频断点上传

什么是断点续传 通常视频文件都比较大&#xff0c;所以对于媒资系统上传文件的需求要满足大文件的上传要求。http协议本身对上传文件大小没有限制&#xff0c;但是客户的网络环境质量、电脑硬件环境等参差不齐&#xff0c;如果一个大文件快上传完了网断了没有上传完成&#xf…

Docker安装部署一本通:从Linux到Windows,全面覆盖!(网络资源精选)

文章目录 📖 介绍 📖🏡 说明 🏡⚓️ 相关链接 ⚓️📖 介绍 📖 随着容器技术的飞速发展,Docker已成为现代软件开发和运维不可或缺的工具。然而,不同平台下的Docker安装部署方式各异,这常常让初学者感到困惑。本文将为您详细梳理各平台下Docker的安装部署方法,帮…

spring boot 集成kafka ,并且实现 发送信息,进行消费信息(亲测有效)

目录 1 目标2 实现 1 目标 有一个spring boot 项目&#xff0c;现在要集成kafka &#xff0c;并且要实现 生产者&#xff0c;消费者信息&#xff1b; 前提是我们要有一个kafka 软件&#xff0c;也就是kafka 是一个软件&#xff0c;我们得安装成功&#xff0c;并且可以访问 k…

算法课程笔记——二维DP

算法课程笔记——二维DP

什么是电脑监控软件?哪些监控软件好用?

电脑监控软件是一种用于监控和管理计算机系统和数据的工具。它可以对计算机的使用情况进行实时监控&#xff0c;记录用户的操作行为&#xff0c;并及时发出警报&#xff0c;以防止数据泄露、违规操作和其他安全问题的发生。在当今信息时代&#xff0c;保护企业和个人信息安全变…

AI编码时代到来?实现编程梦想的利器—Baidu Comate测评

文章目录 Comate智能编码是什么&#xff1f;Comate支持的环境 Comate应用安装实际操作对话式生成代码生成代码注释智能单测项目测试调优功能 总结 Comate智能编码是什么&#xff1f; 在如今这个拥抱AI的时代&#xff0c;市面上已经产出了很多Ai代码助手&#xff0c;如果你还没…

TradingView 使用方法

【前言】最近项目中用到了Tradingview中的K线图,基于以前从未使用过,写此篇文章记录一下Tradingview的使用。 【目标】 1 会使用Tradingview中k线图的渲染方式 2 了解一些基本的用法 一 简介 Tradingview是一个价格图表和分析软件,提供免费和付费选项,为优秀的交易技术分析…

java中的变量、数据类型、人机交互

变量 变量要素 1、类型&#xff1b;每一个变量都需要定义类型&#xff08;强类型&#xff09;其它语言有弱类型&#xff08;js&#xff09; 2、变量名&#xff1b; 3、存储的值&#xff1b; 声明方式&#xff1a; 数据类型 变量名 变量值&#xff1b; public static vo…

电商大数据的采集||电商大数据关键技术【基于Python】

.电商大数据采集API 什么是大数据&#xff1f; 1.大数据的概念 大数据即字面意思&#xff0c;大量数据。那么这个数据量大到多少才算大数据喃&#xff1f;通常&#xff0c;当数据量达到TB乃至PB级别时&#xff0c;传统的关系型数据库在处理能力、存储效率或查询性能上可能会遇…

API接口调用|京东API接口|淘宝API接口

什么是电商API接口&#xff1a; 电商API接口是电商服务平台对外提供的一种接口服务&#xff0c;允许第三方开发者通过编程方式与电商系统进行数据交互和功能调用。 这些接口提供了一种标准化的方法来获取、更新或处理电商平台上的商品信息、订单状态、用户数据、支付信息、物流…

基于Spring Boot的汉服文化网站设计与实现

基于Spring Boot的汉服文化网站设计与实现 开发语言&#xff1a;Java 框架&#xff1a;springboot JDK版本&#xff1a;JDK1.8 数据库工具&#xff1a;Navicat11 开发软件&#xff1a;eclipse/myeclipse/idea 系统部分展示 系统功能界面图&#xff0c;在系统首页可以查看首页…

nvcc: command not found

nvcc: command not found nvcc命令是 NVIDIA CUDA 编译器&#xff0c;就类似于gcc是c语言的编译器&#xff0c;用于编译 CUDA 代码并生成 GPU 可执行文件。由于程序是要经过编译器编程成可执行的二进制文件&#xff0c;而cuda程序有两种代码&#xff0c;一种是运行在CPU上的ho…

【Windows】Windows电脑如何给hosts添加解析

前言 hosts是一个没有扩展名的系统文件&#xff0c;在浏览器输入一个我们想要登录的网站时&#xff0c;电脑系统会自动帮助我们在hosts文件中寻找对应的IP地址&#xff0c;然后打开网站&#xff0c;如果找不到对应IP&#xff0c;电脑就需要对域名和IP地址进行解析。当对一个网…