信号量操作。
1. 信号量相关函数
1.1 信号量声明
信号量类型为sem_t
,本质上是长整型的数。
//semaphores
sem_t mutex;
1.2 信号量初始化
使用函数sem_init对信号量进行初始化。
#include <semaphore.h>
// initialize an unnamed semaphore
int sem_init(sem_t *sem, int pshared, unsigned int value);
参数:
pshared
,若为0,则信号量在线程间共享;若为非0,则信号量在进程间共享
返回值:
- 0 on success
- -1 on error,
errno
is set to indicate the error.
1.3 加锁
使用函数sem_wait,
#include <semaphore.h>
// lock a semaphore
// decrements (locks) the semaphore pointed to by sem.
int sem_wait(sem_t *sem);
// same as sem_wait(), except that if the decrement cannot be immediately performed, then call returns an error
int sem_trywait(sem_t *sem);
// same as sem_wait(), except that abs_timeout specifies a limit on the amount of time that the call should block if the decrement cannot be immediately performed.
int sem_timedwait(sem_t *restrict sem, const struct timespec *restrict abs_timeout);
1.4 解锁
使用函数sem_post,
#include <semaphore.h>
// unlock a semaphore
int sem_post(sem_t *sem);
1.5 释放信号量
使用函数sem_destroy,
#include <semaphore.h>
// destroy an unnamed semaphore
int sem_destroy(sem_t *sem);
2. 一个实例
#include <semaphore.h>
#include <stdlib.h>
int main(){
// declare a semaphore
sem_t mutex;
//init
sem_init(&mutex, 0, 1);
// lock and unlock
sem_wait(&mutex);
// critical section
sem_post(&mutex);
// destroy the semaphore
sem_destroy(&mutex);
return EXIT_SUCCESS;
}
编译的时候,加上选项-pthread
,
gcc -pthread -o sem_example sem_example.c
-pthread Link with the POSIX threads library. On some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking.