作用
信号是通过初始化一定数量的许可证,通过限制获得许可证的线程数量来阻塞未获取许可证达的线程,达到限制对特定资源访问的线程数量。
实现原理
所有多线程访问的控制方式归根结底都是对可共享地址进行管理,可以是简单的类似全局变量做的计数器判断,可以共享内存的数据结构的操作。
接口函数
new(): Creat a semaphore with a specified number kerys;
get(): OBtian one or more keys from the busket;
put(): Return one or more kyes into the bucker;
try_get(): Try to obtian one or maor keys without blocking;
使用举例
单许可证,两线程竞争:
sem = new(1) process 1: sem.get(1); .... sem.put(1); process 1: sem.get(1); .... sem.put(1);
多许可证,多线程竞争
sem = new(5) process 1: sem.get(2); .... sem.put(2); process 1: sem.get(2); .... sem.put(2); process 2: sem.get(2); .... sem.put(2);