头文件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”。

原文地址:https://www.cnblogs.com/aaronwxb/p/2546412.html