天天看點

4線程同步:信号量

1信号量

信号量可以有n把鎖。

依賴的頭檔案

#include <semaphore.h>

函數聲明

sem_t表示信号量

int sem_init(sem_t *sem, int pshared,unsigned int value);

名稱:

sem_init

功能:

頭檔案:

函數原形:

int sem_init(sem_t *sem, int pshared, unsigned int value);

參數:

傳回值:

sem_init() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error.

int sem_wait(sem_t *sem);

int sem_trywait(sem_t *sem);

sem_wait

sem_trywait

lock a semaphore 一直阻塞等待直到信号量

> 0.

all of these functions return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate

the error.

int sem_timedwait(sem_t *sem, const structtimespec *abs_timeout);

sem_timedwait

lock a semaphore,阻塞等待若幹時間直到信号量 > 0

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

int sem_post(sem_t *sem);

sem_post

unlock a semaphore,使信号量加1。

sem_post() returns 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

int sem_destroy(sem_t *sem);

sem_destroy

destroy an unnamed semaphore釋放信号量。和sem_init對應

sem_destroy() return 0 on success;on error,-1 is returned,an errno is set to indicate the error.

案例說明:

#include <stdlib.h>

#include <pthread.h>

#include <stdio.h>

#include <unistd.h>

#define num 5

int queue[num];

sem_t blank_number,product_number;

void *producer(void *arg)

{

   int p = 0;

   while(1) {

       //blank_num = 5生産者最多生産5個

       //一直阻塞等待信号量大于0

       sem_wait(&blank_number);

       queue[p] = rand() % 1000 + 1;

       printf("produce %d\n",queue[p]);

       //product_number = 0 ->1

       //使信号量加1

       sem_post(&product_number);

       p = (p + 1) % num;

       sleep(rand() % 5);

   }

}

void *consumer(void *arg) {

   int c = 0;

   while (1) {

       //等待信号量大于0

       sem_wait(&product_number);

       printf("consume %d\n",queue[c]);

       queue[c] = 0;

       sem_post(&blank_number);

       c = (c + 1) % num;

int main(int argc ,char *argv[])

   pthread_t pid,cid;

   //将blank_num信号量初始化的值為5

   sem_init(&blank_number,0,num);

   //将product_number信号量初始化的值變為0

   sem_init(&product_number,0,0);

   pthread_create(&pid,null,producer,null);

   pthread_create(&cid,null,consumer,null);

   pthread_join(pid,null);

   pthread_join(cid,null);

   sem_destroy(&blank_number);

   sem_destroy(&product_number);

   return 0;

運作結果:

4線程同步:信号量