目录

信号量和P、V原语

信号量集结构体

信号量操作接口

semget

semctl

semop

封装Sem

关于建造者模式


信号量和P、V原语

信号量和 PV 原语由 Dijkstra (迪杰斯特拉)提出

信号量值含义

  • S>0: S 表⽰可⽤资源的个数
  • S=0: 表⽰⽆可⽤资源,⽆等待进程
  • S<0: |S| 表⽰等待队列中进程个数

信号量结构体伪代码

//信号量本质上是⼀个计数器
struct semaphore
{
    int value;
    pointer_PCB queue;
}

P原语

P(s)
{
    s.value = s.value--;
    if (s.value < 0)
    {
        // 该进程状态置为等待状状态
        // 将该进程的PCB插⼊⼊相应的等待队列s.queue末尾
    }
}

V原语

V(s)
{
    s.value = s.value++;
    if (s.value > 0)
    {
        // 唤醒相应等待队列s.queue中等待的⼀⼀个进程
        // 改变其状态为就绪态
        // 并将其插⼊OS就绪队列
    }
}

信号量集结构体


The semid_ds data structure is defined in <sys / sem.h> as follows :
struct semid_ds {
    struct ipc_perm sem_perm; /* Ownership and permissions */
    time_t sem_otime; /* Last semop time */
    time_t sem_ctime; /* Last change time */
    unsigned long sem_nsems; /* No. of semaphores in set */
};
The ipc_perm structure is defined as follows(the highlighted fields
    are settable using IPC_SET) :
    struct ipc_perm {
    key_t __key; /* Key supplied to semget(2) */
    uid_t uid; /* Effective UID of owner */
    gid_t gid; /* Effective GID of owner */
    uid_t cuid; /* Effective UID of creator */
    gid_t cgid; /* Effective GID of creator */
    unsigned short mode; /* Permissions */
    unsigned short __seq; /* Sequence number */
};

信号量操作接口

semget

NAME
semget - get a System V semaphore set identifier

SYNOPSIS
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semget(key_t key, int nsems, int semflg);
RETURN VALUE
If successful, the return value will be the semaphore set identifier
(a nonnegative integer), otherwise, -1 is returned, with errno indicating the
error.

参数介绍

  • key: 信号量集的键值,同消息队列和共享内存
  • nsems: 信号量集中信号量的个数
  • semflg: 同消息队列和共享内存

semctl

NAME
semctl - System V semaphore control operations
SYNOPSIS
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semctl(int semid, int semnum, int cmd, ...);
This function has three or four arguments, depending on cmd.When there are four, the fourth has the type union semun.The calling program must define this union as follows :
    union semun {
    int val; /* Value for SETVAL */
    struct semid_ds* buf; /* Buffer for IPC_STAT, IPC_SET */
    unsigned short* array; /* Array for GETALL, SETALL */
    struct seminfo* __buf; /* Buffer for IPC_INFO
    (Linux-specific) */
};
RETURN VALUE
On failure, semctl() returns - 1 with errno indicating the error.
Otherwise, the system call returns a nonnegative value depending on
cmd as follows :
GETNCNT the value of semncnt.
GETPID the value of sempid.
GETVAL the value of semval.
GETZCNT the value of semzcnt.
IPC_INFO the index of the highest used entry in the kernel's internal
array recording information about all semaphore sets. (This information can
    be used with repeated SEM_STAT or
    SEM_STAT_ANY operations to obtain information about all semaphore sets
    on the system.)
    SEM_INFO as for IPC_INFO.
    SEM_STAT the identifier of the semaphore set whose index was given in
    semid.
    SEM_STAT_ANY as for SEM_STAT.
    All other cmd values return 0 on success.

参数介绍
  • semid: 由 semget 返回的信号集标识码
  • semnum: 信号集中信号量的序号

semnum: semctl() performs the control operation specified by cmd on the
System V semaphore set identified by semid, or on the semnum - th semaphore of
that set. (The semaphores in a set are numbered starting at 0.)

cmd: 将要采取的动作, 具体动作看 man ⼿册

semop

NAME
semop, semtimedop - System V semaphore operations
SYNOPSIS
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semop(int semid, struct sembuf* sops, size_t nsops);
semop() performs operations on selected semaphores in the set indicated by
semid.Each of the nsops elements in the array pointed to by sops is a
structure that specifies an operation to be performed on a single semaphore.
The elements of this structure are of type struct sembuf, containing the
following members :
unsigned short sem_num; /* semaphore number */
short sem_op; /* semaphore operation :-1,P操作。1,V操作
*/
short sem_flg; /* operation flags */
Flags recognized in sem_flg are IPC_NOWAIT and SEM_UNDO.If an operation specifies SEM_UNDO, it will be automatically undone when the process terminates.
RETURN VALUE
If successful, semop() and semtimedop() return 0; otherwise they
return -1 with errno indicating the error.

参数介绍

  • semid: 是该信号量的标识码,也就是 semget 函数的返回值
  • sops: 指向⼀个结构 sembuf 的指针
  • nsops: sops 对应的信号量的个数,也就是可以同时对多个信号量进⾏PV操作

封装Sem

我们使⽤信号量,简化信号量使⽤,测试使⽤⼆元信号量进⾏显⽰器交替打印

Sem.hpp

#pragma once#include <iostream>
#include <string>
#include <memory>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>const std::string pathname = "/tmp";
int proj_id = 0x77;#define GET_SEM IPC_CREAT // 不给权限
#define BUILD_SEM (IPC_CREAT | IPC_EXCL | 0666)// 只关注使用和删除
class Semaphore
{
public:Semaphore(int semid, int flag) : _semid(semid), _flag(flag){}void P(){struct sembuf sb; // 该结构系统提供sb.sem_num = 0;sb.sem_op = -1;sb.sem_flg = SEM_UNDO;int n = ::semop(_semid, &sb, 1);(void)n;}void V(){struct sembuf sb;sb.sem_num = 0;sb.sem_op = 1;sb.sem_flg = SEM_UNDO;int n = ::semop(_semid, &sb, 1);(void)n;}~Semaphore(){if(_flag == GET_SEM) return;// 让信号量自动销毁// 如果销毁信号量集合:The argument semnum is ignoredint n = ::semctl(_semid, 0, IPC_RMID);(void)n;std::cout << "sem set destroy!" << std::endl;}private:int _semid;int _flag;
};using sem_sptr = std::shared_ptr<Semaphore>;// 使用一下简单的建造者模式,用它来构建单sem
class SemaphoreBuilder
{
public:SemaphoreBuilder() : _val(-1){}SemaphoreBuilder &SetVal(int val){_val = val;return *this; // 支持连续访问}sem_sptr Build(int flag){// 0. 先做一下简单的合法性判断if (_val < 0){std::cerr << "you must init first!" << std::endl;return nullptr;}// 1. 申请key值key_t k = ::ftok(pathname.c_str(), proj_id);if (k < 0)exit(1);// 2. 根据初始值,创建信号量集合int semid = ::semget(k, 1, flag); // 这里让信号量集合中,只创建一个信号量就够用了if (semid < 0)exit(2);if (BUILD_SEM == flag){// 3. 初始化信号量union semun // 该联合体系统不提供,需要我们自己定义{int val;               /* Value for SETVAL */struct semid_ds *buf;  /* Buffer for IPC_STAT, IPC_SET */unsigned short *array; /* Array for GETALL, SETALL */struct seminfo *__buf; /* Buffer for IPC_INFO(Linux-specific) */} un;un.val = _val; // 设置为初始值int n = ::semctl(semid, 0, SETVAL, un);if (n < 0)exit(3);}// 4. 创建并返回信号量集合return std::make_shared<Semaphore>(semid, flag);}~SemaphoreBuilder(){}private:int _val; // 所有信号量的初始值
};

Writer.cc:测试信号量接口

#include "Sem.hpp"
#include <cstdio>
#include <time.h>
#include <unistd.h>int main()
{SemaphoreBuilder sb;auto fsem = sb.SetVal(1).Build(BUILD_SEM); // 创建信号量集合,只有一个信号量,初始化成为1,就是当做锁来进行使用if (fork() == 0){auto csem = sb.Build(GET_SEM);int cnt = 10;while (cnt--){csem->P();printf("C");fflush(stdout);usleep(rand() % 95270);printf("C ");usleep(rand() % 43990);fflush(stdout);csem->V();}exit(0);}int cnt = 50;while (cnt--){fsem->P();printf("F");fflush(stdout);usleep(rand() % 95270);printf("F ");usleep(rand() % 43990);fflush(stdout);fsem->V();}return 0;
}

结论

  • System V 信号量⽣命周期也是随内核的
  • ipcs -s && ipcrm -s semid

关于建造者模式

Sem_V.hpp
#ifndef SEM_HPP
#define SEM_HPP#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>const std::string SEM_PATH = "/tmp";
const int SEM_PROJ_ID = 0x77;
const int defaultnum = 1;
#define GET_SEM (IPC_CREAT)
#define BUILD_SEM (IPC_CREAT | IPC_EXCL)///////////////////////////先设计建造者模式的代码结构////////////// 一个把整数转十六进制的函数
std::string intToHex(int num)
{char hex[64];snprintf(hex, sizeof(hex), "0x%x", num);return std::string(hex);
}// 产品类, 只需要关心自己的使用即可(删除)
// 这里的Semaphore不是一个信号量!!而是一个信号量集合!!,要指明你要PV操作哪一个信号量!!
class Semaphore
{
private:void PV(int who, int data){struct sembuf sem_buf;sem_buf.sem_num = who;        // 信号量编号,从0开始sem_buf.sem_op = data;      // S + sem_buf.sem_opsem_buf.sem_flg = SEM_UNDO; // 不关心int n = semop(_semid, &sem_buf, 1);if (n < 0){std::cerr << "semop PV failed" << std::endl;}}
public:Semaphore(int semid) : _semid(semid){}int Id() const{return _semid;}void P(int who){PV(who, -1);}void V(int who){PV(who, 1);}~Semaphore(){if (_semid >= 0){int n = semctl(_semid, 0, IPC_RMID);if (n < 0){std::cerr << "semctl IPC_RMID failed" << std::endl;}std::cout << "Semaphore " << _semid << " removed" << std::endl;}}private:int _semid;// key_t _key; // 信号量集合的键值// int _perm;  // 权限// int _num;   // 信号量集合的个数
};// 建造者接口
class SemaphoreBuilder
{
public:virtual ~SemaphoreBuilder() = default;virtual void BuildKey() = 0;virtual void SetPermission(int perm) = 0;virtual void SetSemNum(int num) = 0;virtual void SetInitVal(std::vector<int> initVal) = 0;virtual void Build(int flag) = 0;virtual void InitSem() = 0;virtual std::shared_ptr<Semaphore> GetSem() = 0;
};// 具体建造者类
class ConcreteSemaphoreBuilder : public SemaphoreBuilder
{
public:ConcreteSemaphoreBuilder() {}virtual void BuildKey() override{// 1. 构建键值std::cout << "Building a semaphore" << std::endl;_key = ftok(SEM_PATH.c_str(), SEM_PROJ_ID);if (_key < 0){std::cerr << "ftok failed" << std::endl;exit(1);}std::cout << "Got key: " << intToHex(_key) << std::endl;}virtual void SetPermission(int perm) override{_perm = perm;}virtual void SetSemNum(int num) override{_num = num;}virtual void SetInitVal(std::vector<int> initVal) override{_initVal = initVal;}virtual void Build(int flag) override{// 2. 创建信号量集合int semid = semget(_key, _num, flag | _perm);if (semid < 0){std::cerr << "semget failed" << std::endl;exit(2);}std::cout << "Got semaphore id: " << semid << std::endl;_sem = std::make_shared<Semaphore>(semid);}virtual void InitSem() override{if (_num > 0 && _initVal.size() == _num){// 3. 初始化信号量集合for (int i = 0; i < _num; i++){if (!Init(_sem->Id(), i, _initVal[i])){std::cerr << "Init failed" << std::endl;exit(3);}}}}virtual std::shared_ptr<Semaphore> GetSem() override{ return _sem; }
private:bool Init(int semid, int num, int val){union semun{int val;               /* Value for SETVAL */struct semid_ds *buf;  /* Buffer for IPC_STAT, IPC_SET */unsigned short *array; /* Array for GETALL, SETALL */struct seminfo *__buf; /* Buffer for IPC_INFO(Linux-specific) */} un;un.val = val;int n = semctl(semid, num, SETVAL, un);if (n < 0){std::cerr << "semctl SETVAL failed" << std::endl;return false;}return true;}private:key_t _key;                      // 信号量集合的键值int _perm;                       // 权限int _num;                        // 信号量集合的个数std::vector<int> _initVal;       // 初始值std::shared_ptr<Semaphore> _sem; // 我们要创建的具体产品
};// 指挥者类
class Director
{
public:void Construct(std::shared_ptr<SemaphoreBuilder> builder, int flag, int perm = 0666, int num = defaultnum, std::vector<int> initVal = {1}){builder->BuildKey();builder->SetPermission(perm);builder->SetSemNum(num);builder->SetInitVal(initVal);builder->Build(flag);if (flag == BUILD_SEM){builder->InitSem();}}
};#endif // SEM_HPP

Writer.cc

#include "Sem_V.hpp"
#include <unistd.h>
#include <ctime>
#include <cstdio>int main()
{// 基于抽象接口类的具体建造者std::shared_ptr<SemaphoreBuilder> builder = std::make_shared<ConcreteSemaphoreBuilder>();// 指挥者对象std::shared_ptr<Director> director = std::make_shared<Director>();// 在指挥者的指导下,完成建造过程director->Construct(builder, BUILD_SEM, 0600, 3, {1, 2, 3});// 完成了对象的创建的过程,获取对象auto fsem = builder->GetSem();// sleep(10);// SemaphoreBuilder sb;// auto fsem = sb.SetVar(1).build(BUILD_SEM, 1);srand(time(0) ^ getpid());pid_t pid = fork();// 我们期望的是,父子进行打印的时候,C或者F必须成对出现!保证打印是原子的.if (pid == 0){director->Construct(builder, GET_SEM);auto csem = builder->GetSem();while (true){// csem->P(0);printf("C");usleep(rand() % 95270);fflush(stdout);printf("C");usleep(rand() % 43990);fflush(stdout);// csem->V(0);}}while (true){// fsem->P(0);printf("F");usleep(rand() % 95270);fflush(stdout);printf("F");usleep(rand() % 43990);fflush(stdout);// fsem->V(0);}return 0;
}

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

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

机器学习(11):岭回归Ridge

岭回归是失损函数通过添加所有权重的平方和的乘积(L2)来惩罚模型的复杂度。均方差除以2是因为方便求导&#xff0c;w_j指所有的权重系数, λ指惩罚型系数&#xff0c;又叫正则项力度特点:岭回归不会将权重压缩到零&#xff0c;这意味着所有特征都会保留在模型中&#xff0c;但它…

调整Idea缓存目录,释放C盘空间

本文使用 Idea2024 Idea 会将一些配置默认缓存在C盘&#xff0c;使用久了会占用大量空间&#xff08;本人的Idea占用了将近5个G&#xff0c;以至于不得不进行迁移&#xff09; 缓存目录主要涉及以下四个目录&#xff0c;四个目录可以分为两组&#xff0c;每组目录必须一起调整 …

手搓栅格工具-山体阴影

一、概述 山体阴影工具通过为栅格中的每个像元确定照明度&#xff0c;来获取表面的假定照明度。 通过设置假定光源的位置并计算每个像元相对于相邻像元的照明度值来实现此目的。 它可以显著增强用于分析或图形显示的表面的可视化效果&#xff0c;尤其是在使用透明度时。 默认情…

Censtos docker安装方法

#设置防火墙 systemctl stop firewalld.service setenforce 0 #安装依赖包 yum install -y yum-utils device-mapper-persistent-data lvm2 #yum-utils&#xff1a;提供了 yum-config-manager 工具。 #device mapper&#xff1a; 是Linux内核中支持逻辑卷管理的通用设备映射机制…

单片机51 day46

单片机 一&#xff1a;基础概念 一&#xff1a;单片机最小系统 单片机&#xff1a;电源时钟&#xff08;晶振&#xff09;复位 //实现的最小组件 电源&#xff1a;5V直流 时钟(晶振)&#xff1a;决定系统运行的速率 一般12M&#xff08;不超过50M&#xff09;&#xff0c…

【无标题】解锁未来无线网络的无限可能——Mesh自组网设备

在科技迅猛发展的今天&#xff0c;无线网络已经成为了现代生活不可或缺的一部分。无论是在家庭中娱乐观看视频、在线游戏&#xff0c;还是在企业中进行办公、远程协作&#xff0c;网络的稳定性和覆盖范围都直接影响着我们的使用体验。传统的Wi-Fi网络在面临多设备同时连接或大面…

Libevent(5)之使用教程(4)工具

Libevent(5)之使用教程(4)工具函数 Author: Once Day Date: 2025年8月3日 一位热衷于Linux学习和开发的菜鸟&#xff0c;试图谱写一场冒险之旅&#xff0c;也许终点只是一场白日梦… 漫漫长路&#xff0c;有人对你微笑过嘛… 本文档翻译于&#xff1a;Fast portable non-blo…

Linux指令(3):

1. cal指令&#xff1a;我们的cal指令有日历的意思看上面&#xff0c;我们输入一个cal指令&#xff0c;可以查看当前月的日历&#xff0c;我们给cal指令后面加上 - 3&#xff0c;他就会显示这个月为中间的三个月的日历&#xff0c;但是-4 不行&#xff0c;-5 也不行。只能 - 3。…

MLS平滑滤波

1.前言 最近在学习&#xff0c;因此查阅相关资料&#xff0c;该怎么表述感觉有些困难 2.代码 2.1代码1 使用全局坐标系 参考&#xff1a;python点云移动最小二乘法(Moving Least Squares)平滑_移动最小二乘法python-CSDN博客 def Moving_Least_Squares_Smoothing_v1_expla…

华为2288H V5服务器闪红灯 无法开机案例

广东某客户1台华为2288H V5服务器&#xff0c;由于单位外围电力维修导致服务器有过一次异常断电。结果来电之后发现服务器无法开机&#xff0c;开机面板上有个红色心跳指示灯&#xff0c; 工程师到客户现场后通过192.168.2.100登陆到2288H V5服务器的BMC管理口&#xff0c;打算…

SRIO入门之官方例程仿真验证

仿真SRIO事务时序仿真之前先完成下面两步操作&#xff1a;1.Vivado软件版本2020.1&#xff0c;创建好工程及SRIO的IP核2.右键综合化的IP核&#xff0c;然后选择打开IP示例工程直接运行仿真分别将request和response两个模块添加到仿真窗口进行查看运行1000us左右就可以看到信号动…

CMake进阶: 使用FetchContent方法基于gTest的C++单元测试

目录 1.前言 2.FetchContent详解 2.1.FetchContent简介 2.2.FetchContent_Declare 2.2.1.简介 2.2.2.关键特性 2.2.3.常见示例 2.3.FetchContent_MakeAvailable 2.3.1.简介 2.3.2.核心功能与工作流程 2.3.3.示例用法 2.3.4.关键特性 2.3.5.常见问题与解决方案 3.…

亚马逊广告投放:如何减少无效曝光提高ROI

“为什么广告花费高但转化率低&#xff1f;”“如何判断关键词是否值得继续投放&#xff1f;”“曝光量暴涨但订单没增加怎么办&#xff1f;”“ACOS居高不下该如何优化&#xff1f;”“手动广告和自动广告的预算怎么分配&#xff1f;”如果你也在为这些问题头疼&#xff0c;说…

Ethereum:拥抱开源,OpenZeppelin 未来的两大基石 Relayers 与 Monitor

不知道大家是否注意到&#xff0c;OpenZeppelin 正在经历一次重大的战略转型。他们决定在 2026 年 7 月 1 日正式关闭其广受好评的 SaaS 平台——Defender&#xff0c;并将重心全面转向开源工具的建设。 这一举动在社区引发了广泛的讨论&#xff0c;也标志着 OpenZeppelin 希望…

HFSS许可监控与分析

在电磁仿真领域&#xff0c;HFSS&#xff08;High Frequency Structure Simulator&#xff09;因其卓越的性能和广泛的应用而受到用户的青睐。然而&#xff0c;随着企业和研究机构对HFSS使用需求的不断增长&#xff0c;如何有效监控和分析HFSS许可证的使用情况&#xff0c;以确…

【前端:Html】--1.3.基础语法

目录 1.Html--文件路径 2.Html--头部元素 2.1.head元素 2.2.title元素 2.3.style元素 2.4.link元素 2.5.meta元素 2.6.script元素 2.7.base 3.Html--布局技巧 3.1.CSS Float 浮动布局 3.2.CSS Flexbox 布局 3.3.CSS Grid 网格布局 3.Html--响应式web设计 3.1.设…

Java 中 Nd4j 中的 INDArray 经过 reshape 之后数据丢失(rank = 0)

问题&#xff1a; 数据经过&#xff1a; INDArray inputArray Nd4j.create(input); // 将整个输入数组转换为 INDArray INDArray accs inputArray.get(NDArrayIndex.interval(0, imuNum * 3)).reshape(imuNum, 3, 1); // 加速度部分 INDArray oris inputArray.get(NDArrayIn…

正点原子阿波罗STM32F429IGT6移植zephyr rtos(四)---在独立的应用工程里使用MPU6050

硬件平台&#xff1a;正点原子阿波罗STM32F429IGT6 zephyr版本&#xff1a;Zephyr version 4.2.0 开发环境&#xff1a;wsl ubuntu 24.4 前景提要&#xff1a; 正点原子阿波罗STM32F429IGT6移植zephyr rtos&#xff08;三&#xff09;---创建一个独立的应用工程-CSDN博客 一.修…

SAP_MMFI模块-质保金标准解决方案详解

一、业务背景 在许多企业的采购业务中,尤其是设备采购、工程项目或关键物料供应,通常会与供应商约定一笔质保金(或称保留金)。这笔款项在货物交付验收后并不会立即支付,而是会被扣留一段时间(如一年),作为供应商产品质量的保证。 核心业务痛点: 在没有系统化管理的…

Stanford CS336 assignment1 | Byte-Pair Encoding (BPE) Tokenizer

BPE一、 BPETrain1、 unicode standard and unicode encoding2、 子词分词(subword tokenization)3、 BPE的训练a、 Vocabulary initializationb、 Pre-tokenizationc、 Compute BPE merges4、 train_BPE更多实现上的细节二、 BPETokenizerinit函数from_filesencodedecodeencod…