| 
									
										
										
										
											2017-08-11 22:11:17 +08:00
										 |  |  | /* | 
					
						
							|  |  |  | 	MIT License http://www.opensource.org/licenses/mit-license.php
 | 
					
						
							|  |  |  | 	Author Tobias Koppers @sokra | 
					
						
							|  |  |  | */ | 
					
						
							|  |  |  | "use strict"; | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | class Semaphore { | 
					
						
							|  |  |  | 	constructor(available) { | 
					
						
							|  |  |  | 		this.available = available; | 
					
						
							|  |  |  | 		this.waiters = []; | 
					
						
							| 
									
										
										
										
											2018-04-12 21:54:35 +08:00
										 |  |  | 		this._continue = this._continue.bind(this); | 
					
						
							| 
									
										
										
										
											2017-08-11 22:11:17 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	acquire(callback) { | 
					
						
							| 
									
										
										
										
											2018-02-25 09:00:20 +08:00
										 |  |  | 		if (this.available > 0) { | 
					
						
							| 
									
										
										
										
											2017-08-11 22:11:17 +08:00
										 |  |  | 			this.available--; | 
					
						
							|  |  |  | 			callback(); | 
					
						
							|  |  |  | 		} else { | 
					
						
							|  |  |  | 			this.waiters.push(callback); | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	release() { | 
					
						
							| 
									
										
										
										
											2018-04-12 21:54:35 +08:00
										 |  |  | 		this.available++; | 
					
						
							| 
									
										
										
										
											2018-02-25 09:00:20 +08:00
										 |  |  | 		if (this.waiters.length > 0) { | 
					
						
							| 
									
										
										
										
											2018-04-12 21:54:35 +08:00
										 |  |  | 			process.nextTick(this._continue); | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	_continue() { | 
					
						
							|  |  |  | 		if (this.available > 0) { | 
					
						
							|  |  |  | 			if (this.waiters.length > 0) { | 
					
						
							|  |  |  | 				this.available--; | 
					
						
							|  |  |  | 				const callback = this.waiters.pop(); | 
					
						
							|  |  |  | 				callback(); | 
					
						
							|  |  |  | 			} | 
					
						
							| 
									
										
										
										
											2017-08-11 22:11:17 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | module.exports = Semaphore; |