POSIX semaphore

无名信号量

  • 除非使用共享内存,否则只能控制通同一进程的线程
1
2
3
4
// 初始化信号量sem的初始值为value
int sem_init (sem_t *__sem, int __pshared, unsigned int __value)
// 删除信号量
int sem_destroy (sem_t *__sem)

有名信号量

1
2
3
4
5
6
7
8
9
10
11
// name是名称
// oflag:O_CREAT:如果信号量不存在则新建,存在直接返回
// 如果为O_CREAT|O_EXCL,则已存在的话会返回错误
// mode:
// value:初始值
sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);
// 关闭进程内信号量
int sem_close (sem_t *__sem)
// 从内核中删除有名信号量
int sem_unlink (const char *__name)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int pid = fork();
if (pid<0) {
cout << "fork failed";
}
if (pid==0) {
sem_t* sem=sem_open("test", O_CREAT, 0666, 1);
int rs = sem_wait(sem);
if (rs<0) {
cout << "wait failed";
exit(-1);
} else {
cout << "success 1" << endl;
sleep(3);
sem_post(sem);
sem_close(sem);
}
} else {
sem_t* sem=sem_open("test", O_CREAT, 0666, 1);
int rs=sem_wait(sem);
if (rs<0) {
cout << "wait failed";
exit(-1);
} else {
cout << "success 2" << endl;
sleep(3);
sem_post(sem);
sem_close(sem);
}
int tmp;
wait(&tmp);
}

共用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 阻塞获取,值-1
int sem_wait (sem_t *__sem)
// 阻塞超时获取
int sem_timedwait (sem_t *__restrict __sem, const struct timespec *__restrict __abstime)
struct timespec {
__time_t tv_sec; // Seconds
__syscall_slong_t tv_nsec; // Nanoseconds
};
// 非阻塞获取信号量,成功放回0,值-1;失败返回-1
// EINTR:信号处理函数中断调用
// EINVAL:信号量sem值无效
// EAGAIN:信号量不足
int sem_trywait (sem_t *__sem)
// 释放信号量,值+1
int sem_post (sem_t *__sem)
// 获取当前信号量的值,存在sval
int sem_getvalue (sem_t *__restrict __sem, int *__restrict __sval)

参考文献