На Beej Guide, Существуют Постулаты следующегоРазница между семафором и значением операции, которая передается во время вызова semop
«Когда вы первый создать несколько семафоров, они все неинициализированные, он принимает еще один вызов, чтобы отметить их как бесплатно ».
Intially я создал с семафором, как 5.
#define SEM_COUNT 5
semget(sem_key,SEM_COUNT,IPC_CREAT|IPC_EXCL|0600);
Теперь в соответствии с вышеуказанным заявлением от Beej руководства, я должен intiaize на 5 семафоров, чтобы отметить их как бесплатно, позвонив semop.
Чтобы указать семафор как свободный передаю в sem_op как 1
sem_op[0].sem_op=1;
запроса 1. Может ли sem_op значение быть больше, чем один? Например, если он прошел как 3, то что это значит?
Мое понимание для запроса 1: Это количество ресурсов (поток или процесс), которые могут одновременно обращаться к критическому разделу или совместно используемому ресурсу.
Запрос 2. Если мое понимание запроса 1 верное, то счет семафора, который я передаю для semget, - это отдельные семафоры, которые могут использоваться для секвациальных критических разделов. Если я создал счет семафора как 5. Тогда это означает, что я могу использовать 5 критических разделов. Одновременные ресурсы, которые могут получить доступ к этим 5 критическим секциям, будут переданы во время вызова semop. Правильно ли я понимаю?
Примечание: Я использую реализацию сделана для системы V (SYS/sem.h)
Причины этого запросов: Я путать себя, нравится ли sem_op значение как число семафоров свободное (или) количество ресурсов отдельные семафоры бесплатны.
ОБРАЗЕЦ КОД
#include <sys/sem.h>
#include <cstdio>
#include <unistd.h>
#define SEMAPHORE_COUNT 1
void semaphore_wait(int sem_id);
void semaphore_signal(int sem_id);
int main()
{
/* 1.Getting the semaphore Key */
key_t sem_key=ftok("key.txt",'S');
if(0 >= sem_key)
{
perror("Error in getting key: ");
}
else
{
printf("\nSucessfully generated semaphore key. Value %d ",sem_key);
}
/* 2.Attaching the key to semaphore */
int sem_id = semget(sem_key,SEMAPHORE_COUNT,0);
struct sembuf sem_inp;
sem_inp.sem_op=1; /*Semaphore operation: 1:Increment -1:Decrement: Query1: Can this value can be more than 1? what does that means if greater than 1? */
sem_inp.sem_num=0;
sem_inp.sem_flg=SEM_UNDO;
semop(sem_id,&sem_inp,1);
/* 3.Utilizing the semaphore on critical sections */
printf("\n Waiting for semaphore...");
semaphore_wait(sem_id);
printf("\n Acquired semaphore...");
sleep(4);
semaphore_signal(sem_id);
printf("\n Released semaphore...");
return 0;
}
void semaphore_wait(int sem_id)
{
struct sembuf sem_inp;
sem_inp.sem_op=-1; /*Semaphore operation: 1:Increment -1:Decrement */
sem_inp.sem_num=0;
sem_inp.sem_flg=SEM_UNDO;
semop(sem_id,&sem_inp,1);
}
void semaphore_signal(int sem_id)
{
struct sembuf sem_inp;
sem_inp.sem_op=1; /*Semaphore operation: 1:Increment -1:Decrement */
sem_inp.sem_num=0;
sem_inp.sem_flg=SEM_UNDO;
semop(sem_id,&sem_inp,1);
}
Вы отведенной некоторые из кода, что sem_op [0]? вы не определяете его нигде ... Во всяком случае, использование sem_op, предоставляя его в виде semop, неверно. Я предлагаю вам прочитать http://pubs.opengroup.org/onlinepubs/7908799/xsh/semop.html В двух словах - sem_op означает, что тип операции должен выполняться в массиве семафоров атомарно –
@IshayPeled Прикрепленный код –