頭文件semaphore.h 中的常用函數sem_init,sem_wait,sem_post,sem_destroy


NAME

semaphore.h - semaphores ( REALTIME)

SYNOPSIS

[SEM] [Option Start] #include <semaphore.h> [Option End]

DESCRIPTION

The <semaphore.h> header shall define the sem_t type, used in performing semaphore operations. The semaphore may be implemented using a file descriptor, in which case applications are able to open up at least a total of {OPEN_MAX} files and semaphores. The symbol SEM_FAILED shall be defined (see sem_open()).

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    sem_close(sem_t *);
int    sem_destroy(sem_t *);
int    sem_getvalue(sem_t *restrict, int *restrict);
int    sem_init(sem_t *, int, unsigned);
sem_t *sem_open(const char *, int, ...);
int    sem_post(sem_t *);
[TMO][Option Start]
int    sem_timedwait(sem_t *restrict, const struct timespec *restrict);
[Option End]
int    sem_trywait(sem_t *);
int    sem_unlink(const char *);
int    sem_wait(sem_t *);

Inclusion of the <semaphore.h> header may make visible symbols defined in the headers <fcntl.h> and <sys/types.h>.

 

 

信號量用sem_init函數創建的,下面是它的說明:
  #include<semaphore.h>
        int sem_init (sem_t *sem, int pshared, unsigned int value);

        這個函數的作用是對由sem指定的信號量進行初始化,設置好它的共享選項,並指定一個整數類型的初始值。pshared參數控制着信號量的類型。如果pshared的值是0,就表示它是當前里程的局部信號量;否則,其它進程就能夠共享這個信號量。我們現在只對不讓進程共享的信號量感興趣。 (這個參數受版本影響), pshared傳遞一個非零將會使函數調用失敗。

  這兩個函數控制着信號量的值,它們的定義如下所示:
  
  #include <semaphore.h>
        int sem_wait(sem_t * sem);
        int sem_post(sem_t * sem);
 
        這兩個函數都要用一個由sem_init調用初始化的信號量對象的指針做參數。
        sem_post函數的作用是給信號量的值加上一個“1”,它是一個“原子操作”---即同時對同一個信號量做加“1”操作的兩個線程是不會沖突的;而同時對同一個文件進行讀、加和寫操作的兩個程序就有可能會引起沖突。信號量的值永遠會正確地加一個“2”--因為有兩個線程試圖改變它。
        sem_wait函數也是一個原子操作,它的作用是從信號量的值減去一個“1”,但它永遠會先等待該信號量為一個非零值才開始做減法。也就是說,如果你對一個值為2的信號量調用sem_wait(),線程將會繼續執行,介信號量的值將減到1。如果對一個值為0的信號量調用sem_wait(),這個函數就會地等待直到有其它線程增加了這個值使它不再是0為止。如果有兩個線程都在sem_wait()中等待同一個信號量變成非零值,那么當它被第三個線程增加一個“1”時,等待線程中只有一個能夠對信號量做減法並繼續執行,另一個還將處於等待狀態。
         信號量這種“只用一個函數就能原子化地測試和設置”的能力下正是它的價值所在。 還有另外一個信號量函數sem_trywait,它是sem_wait的非阻塞搭檔。

         最后一個信號量函數是sem_destroy。這個函數的作用是在我們用完信號量對它進行清理。下面的定義:
          #include<semaphore.h>
          int sem_destroy (sem_t *sem);
          這個函數也使用一個信號量指針做參數,歸還自己戰勝的一切資源。在清理信號量的時候如果還有線程在等待它,用戶就會收到一個錯誤。
         與其它的函數一樣,這些函數在成功時都返回“0”。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM