【问题标题】:is it possible to have an array of semaphores?是否有可能有一组信号量?
【发布时间】:2021-06-14 08:17:11
【问题描述】:

我正在研究哲学家就餐问题,并且我正在尝试创建一种方法来跟踪共享资源(叉子)。所以我的想法是创建一个信号量数组,这样当我不得不分叉时,我可以通过利用数组中的索引来跟踪哲学家的编号和他的叉子,该索引理想地包含资源。

所以我的问题是,这可能吗?我所做的一切都导致了错误,例如:

char ** sems[5];
sems[0] = struct sembuf a[1] = {{0, 1, 0}};
sems[1] = struct sembuf b[1]
sems[2] = struct sembuf c[1].... and so forth

然而,这显然是不正确的做法。有人可以帮我指出正确的方向吗? .

【问题讨论】:

  • char** 不能存储任意的struct
  • 你是怎么做到的?您可以将结构声明为数组吗?像数组结构 smes[5]?
  • struct x[N],当然。
  • 好的,那我怎样才能独立修改这些信号量呢?就像我如何为每个信号量使用 semop 命令? semop(semID, sems[3], 1);给我一个错误
  • 在我看来,你是想走捷径,真的过度扩张自己。回到基础并学习如何在 C 中声明和使用数组和结构数组,然后再继续深入,这将有所帮助。

标签: c linux system ipc semaphore


【解决方案1】:

是的,有可能,参见Arrays of semaphore and mutual assignment in C

linux 中有两种信号量:SystemV 和 POSIX 信号量 (https://www.tutorialspoint.com/inter_process_communication/inter_process_communication_system_v_posix.htm)

SystemV (sem.h)

内核内置信号量数组存在于使用 SysVinit 作为初始化系统 (SystemV) 的发行版中,请参阅 https://serverfault.com/questions/312982/what-are-the-semaphore-arrays-on-linux

有一个来自 SystemV (sem.h) 的旧信号量库,其中存在一个函数 GETALL,它将所有信号量写入数组

semctl(semid, 2, GETALL, outarray); in How semaphore operations are done for parent & child processes?

POSIX (semaphores.h)

信号量在内核(Ring 0)中维护,它们存储在/dev 文件系统中,参见https://man7.org/linux/man-pages/man7/sem_overview.7.htmlhttps://unix.stackexchange.com/questions/275650/where-is-a-named-semaphore-stored

您可以使用sem_overview()(命名信号量)和shm_overview()(未命名信号量)获得所有信号量的概览

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-01-03
    相关资源
    最近更新 更多