Skip to content
This repository was archived by the owner on Jan 19, 2021. It is now read-only.

Commit 8e84352

Browse files
add lock
1 parent 49beeca commit 8e84352

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/baseTrie.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ export class Trie {
255255
const childRef = child[1] as Buffer
256256
const childKey = key.concat(keyExtension)
257257
const priority = childKey.length
258-
taskExecutor.execute(priority, async (taskCallback: Function) => {
258+
await taskExecutor.execute(priority, async (taskCallback: Function) => {
259259
const childNode = await self._lookupNode(childRef)
260260
taskCallback()
261261
if (childNode) {
@@ -275,7 +275,7 @@ export class Trie {
275275
const childKey = key.slice()
276276
childKey.push(childIndex)
277277
const priority = childKey.length
278-
taskExecutor.execute(priority, async (taskCallback: Function) => {
278+
await taskExecutor.execute(priority, async (taskCallback: Function) => {
279279
const childNode = await self._lookupNode(childRef)
280280
taskCallback()
281281
if (childNode) {

src/prioritizedTaskExecutor.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import Semaphore from 'semaphore-async-await'
2+
13
interface Task {
24
priority: number
35
fn: Function
@@ -10,6 +12,8 @@ export class PrioritizedTaskExecutor {
1012
private currentPoolSize: number
1113
/** The task queue */
1214
private queue: Task[]
15+
/** The Lock */
16+
private lock: Semaphore
1317

1418
/**
1519
* Executes tasks up to maxPoolSize at a time, other items are put in a priority queue.
@@ -21,6 +25,7 @@ export class PrioritizedTaskExecutor {
2125
this.maxPoolSize = maxPoolSize
2226
this.currentPoolSize = 0
2327
this.queue = []
28+
this.lock = new Semaphore(1)
2429
}
2530

2631
/**
@@ -29,15 +34,18 @@ export class PrioritizedTaskExecutor {
2934
* @param priority The priority of the task
3035
* @param fn The function that accepts the callback, which must be called upon the task completion.
3136
*/
32-
execute(priority: number, fn: Function) {
37+
async execute(priority: number, fn: Function) {
38+
await this.lock.acquire()
3339
if (this.currentPoolSize < this.maxPoolSize) {
3440
this.currentPoolSize++
35-
fn(() => {
41+
fn(async () => {
42+
await this.lock.acquire()
3643
this.currentPoolSize--
3744
if (this.queue.length > 0) {
3845
const item = this.queue.shift()
3946
this.execute(item!.priority, item!.fn)
4047
}
48+
this.lock.signal()
4149
})
4250
} else {
4351
if (this.queue.length == 0) {
@@ -70,6 +78,7 @@ export class PrioritizedTaskExecutor {
7078
}
7179
}
7280
}
81+
this.lock.signal()
7382
}
7483

7584
/**

0 commit comments

Comments
 (0)