天天看點

信号量sem_init

信号量的資料類型為結構sem_t,它本質上是一個長整型的數。函數sem_init()用來初始化一個信号量。它的原型為:  

extern int sem_init __p((sem_t *__sem, int __pshared, unsigned int __value));  

sem為指向信号量結構的一個指針;pshared不為0時此信号量在程序間共享,否則隻能為目前程序的所有線程共享;value給出了信号量的初始值。  

函數sem_post( sem_t *sem)用來增加信号量的值。當有線程阻塞在這個信号量上時,調用這個函數會使其中的一個線程不在阻塞,選擇機制同樣是由線程的排程政策決定的。  

函數sem_wait( sem_t *sem)被用來阻塞目前線程直到信号量sem的值大于0,解除阻塞後将sem的值減一,表明公共資源經使用後減少。函數sem_trywait (sem_t *sem )是函數sem_wait()的非阻塞版本,它直接将信号量sem的值減一。  

函數sem_destroy(sem_t*sem)用來釋放信号量sem。 

信号量用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”。

#include<stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <string.h>

#include <pthread.h>

#include <semaphore.h>

sem_t bin_sem;

void *thread_function1(void *arg)

{

 printf("thread_function1--------------sem_wait\n");

 sem_wait(&bin_sem);

 printf("sem_wait\n");

 while (1)

 {

 }

}

void *thread_function2(void *arg)

 printf("thread_function2--------------sem_post\n");

 sem_post(&bin_sem);

 printf("sem_post\n");

int main()

 int res;

 pthread_t a_thread;

 void *thread_result;

 res = sem_init(&bin_sem, 0,0);

 if (res != 0)

  perror("semaphoreinitialization failed");

  printf("sem_init\n");

 res = pthread_create(&a_thread,null, thread_function1, null);

  perror("thread creationfailure");

 printf("thread_function1\n");

 sleep (5);

 printf("sleep\n");

 res = pthread_create(&a_thread,null, thread_function2, null);

sem_init

thread_function1

thread_function1--------------sem_wait

sleep

thread_function2--------------sem_post

sem_wait

sem_post