itsMe
itsMe

Reputation: 51

is it possible to have an array of semaphores?

I am working on the dining philosophers problem, and I am attempting to create a way to keep track of the shared recourse (the forks). So my thinking is to create an array of semaphores, and that way when i have to fork off i can keep track of the philosophers number and his fork for eating by utilizing the index in the array which would ideally contain the recourse.

So my question is, is this possible? Everything i have attempted has resulted in an error such as:

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

however this is obviously the incorrect way to do this. can someone help point me in the right direction? .

Upvotes: 1

Views: 1366

Answers (1)

ralf htp
ralf htp

Reputation: 9422

Yes, is possible, cf Arrays of semaphore and mutual assignment in C

There are two types of semaphores in linux : SystemV and POSIX semaphores (https://www.tutorialspoint.com/inter_process_communication/inter_process_communication_system_v_posix.htm)

SystemV (sem.h)

Kernel-inbuilt semaphore arrays exist in distros that use SysVinit as init system (SystemV), see https://serverfault.com/questions/312982/what-are-the-semaphore-arrays-on-linux

There is an older semaphore library from SystemV (sem.h) in that a function GETALL exists that writes all semaphores to an array

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

POSIX (semaphores.h)

Semaphores are maintained in the kernel (Ring 0), they are stored in /dev filesystem, see https://man7.org/linux/man-pages/man7/sem_overview.7.html and https://unix.stackexchange.com/questions/275650/where-is-a-named-semaphore-stored

You can get an overview over all semaphores using sem_overview() (named semaphores) and shm_overview() (unnamed semaphores)

Upvotes: 2

Related Questions