|
Last change
on this file since ba17441 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
678 bytes
|
| Rev | Line | |
|---|
| [a762898] | 1 | class Semaphore {
|
|---|
| 2 | capacity;
|
|---|
| 3 | available;
|
|---|
| 4 | deferredTasks = [];
|
|---|
| 5 | constructor(capacity) {
|
|---|
| 6 | this.capacity = capacity;
|
|---|
| 7 | this.available = capacity;
|
|---|
| 8 | }
|
|---|
| 9 | async acquire() {
|
|---|
| 10 | if (this.available > 0) {
|
|---|
| 11 | this.available--;
|
|---|
| 12 | return;
|
|---|
| 13 | }
|
|---|
| 14 | return new Promise(resolve => {
|
|---|
| 15 | this.deferredTasks.push(resolve);
|
|---|
| 16 | });
|
|---|
| 17 | }
|
|---|
| 18 | release() {
|
|---|
| 19 | const deferredTask = this.deferredTasks.shift();
|
|---|
| 20 | if (deferredTask != null) {
|
|---|
| 21 | deferredTask();
|
|---|
| 22 | return;
|
|---|
| 23 | }
|
|---|
| 24 | if (this.available < this.capacity) {
|
|---|
| 25 | this.available++;
|
|---|
| 26 | }
|
|---|
| 27 | }
|
|---|
| 28 | }
|
|---|
| 29 |
|
|---|
| 30 | export { Semaphore };
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.