2015-07-08 1 views
0

На 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); 
} 
+0

Вы отведенной некоторые из кода, что sem_op [0]? вы не определяете его нигде ... Во всяком случае, использование sem_op, предоставляя его в виде semop, неверно. Я предлагаю вам прочитать http://pubs.opengroup.org/onlinepubs/7908799/xsh/semop.html В двух словах - sem_op означает, что тип операции должен выполняться в массиве семафоров атомарно –

+0

@IshayPeled Прикрепленный код –

ответ

1

Запрос 1:

sem_op может быть больше, чем один. В таком случае, что число добавляются к разрешениям семафора имеет

Query 2:

Вы предположение о запросе 1 является неправильным. Это не абсолютное количество разрешений, а дополнение к числу таких. Смысл «разрешения семафора» заключается в том, сколько объектов может удерживать этот семафор одновременно. Это означает, например, что если у вас есть 5 нитей, конкурирующих в критическом разделе, защищенном семафором, с тремя разрешениями, то только 3 будут доступны одновременно.

Из инструкции:

The variable sem_op specifies one of three semaphore operations: 

    1. If sem_op is a negative integer and the calling process has alter permission, one of the following shall occur: 

     * If semval(see <sys/sem.h>) is greater than or equal to the absolute value of sem_op, the absolute value of sem_op is subtracted from sem‐ 
      val. Also, if (sem_flg &SEM_UNDO) is non-zero, the absolute value of sem_op shall be added to the semadj value of the calling process for 
      the specified semaphore. 

     * If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately. 

     * If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semncnt associated with 
      the specified semaphore and suspend execution of the calling thread until one of the following conditions occurs: 

      -- The value of semval becomes greater than or equal to the absolute value of sem_op. When this occurs, the value of semncnt associated 
       with the specified semaphore shall be decremented, the absolute value of sem_op shall be subtracted from semval and, if (sem_flg 
       &SEM_UNDO) is non-zero, the absolute value of sem_op shall be added to the semadj value of the calling process for the specified sema‐ 
       phore. 

      -- The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set to [EIDRM] 
       and −1 shall be returned. 

      -- The calling thread receives a signal that is to be caught. When this occurs, the value of semncnt associated with the specified sema‐ 
       phore shall be decremented, and the calling thread shall resume execution in the manner prescribed in sigaction(). 

    2. If sem_op is a positive integer and the calling process has alter permission, the value of sem_op shall be added to semval and, if (sem_flg 
     &SEM_UNDO) is non-zero, the value of sem_op shall be subtracted from the semadj value of the calling process for the specified semaphore. 

    3. If sem_op is 0 and the calling process has read permission, one of the following shall occur: 

     * If semval is 0, semop() shall return immediately. 

     * If semval is non-zero and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately. 

     * If semval is non-zero and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semzcnt associated with the specified semaphore and sus‐ 
      pend execution of the calling thread until one of the following occurs: 

      -- The value of semval becomes 0, at which time the value of semzcnt associated with the specified semaphore shall be decremented. 

      -- The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set to [EIDRM] 
       and −1 shall be returned. 

      -- The calling thread receives a signal that is to be caught. When this occurs, the value of semzcnt associated with the specified sema‐ 
       phore shall be decremented, and the calling thread shall resume execution in the manner prescribed in sigaction(). 

    Upon successful completion, the value of sempid for each semaphore specified in the array pointed to by sops shall be set to the process ID of the 
    calling process. Also, the sem_otime timestamp shall be set to the current time, as described in Section 2.7.1, IPC General Description.