(7)函 sem_trywait():
(8)函数 sem_timedwait() :
(9) 函数 sem_getvalue ():
(10)代码举例验证信号量里的资源数是无限的。这个实验,也是为了猜测 linux 内核里关于信号量的设计,可见, linux 内核只关注信号量管理的资源数量是非负整数即可以。大于0 表示共享资源是空闲的。 <= 0 表示共享资源没有了,线程或进程需要等待。 与 锁 mutex ,条件变量 condition_variable 共同完成多进程多线程的编程,资源共享、互斥与同步。
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <unistd.h>
int main()
{
sem_t semaphore ; int num ;
if (sem_init( &semaphore, 0, 5 ) != 0)
{ // 初始化信号量,只有 5 个共享资源,用于线程间同步
perror("sem_init");
exit(EXIT_FAILURE);
}
sem_wait( &semaphore );
sem_getvalue( &semaphore , &num );
printf("当前的空闲的资源数量%d\n", num); // 应该是 4
sem_post(&semaphore); sem_post(&semaphore); sem_post(&semaphore);
sem_getvalue( &semaphore , &num );
printf("当前的空闲的资源数量%d\n", num); // 应该是 7
sem_destroy(&semaphore); // 销毁信号量
return 0;
}
++ 实验结果验证了上面的结论,谢谢码农论坛老师, 码农论坛老师的信号量讲解在这里,也是编写这个测试例子的思路来源:
(11)
谢谢