-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebAPIThreadPool.js
53 lines (50 loc) · 1.34 KB
/
webAPIThreadPool.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Queue } from './dataStructure.js';
class WebAPIThreadPool {
eventLoop;
constructor() {
this.threadQueue = new Queue();
this.webAPITaskQueue = new Queue();
}
webAPITaskEnQueue(func) {
this.webAPITaskQueue.enqueue(func);
this.allocateThread();
}
allocateThread() {
if (this.threadQueue.size >= 5) {
console.log('Thread is fulled');
} else
this.threadQueue.enqueue(
new WebAPI(
this.onCompleteFunc.bind(this),
this.webAPITaskQueue.dequeue(),
),
);
}
deallocateThread() {
this.threadQueue.dequeue();
}
onCompleteFunc(func) {
console.log(
`Complete async & Macro task send to Macrotask queue => ${func.name}`,
);
this.eventLoop.macrotaskQueue.enqueue(func);
// this.sendMacroToQueue(func);
this.eventLoop.runLoop();
this.deallocateThread();
if (this.webAPITaskQueue.top) this.allocateThread();
}
}
class WebAPI {
constructor(onCompleteFunc, func) {
this.onCompleteFunc = onCompleteFunc;
this.func = func;
this.startAsyncFunction();
}
startAsyncFunction() {
console.log(`Start async => ${this.func.name}`);
if (this.func.ms === 0) this.onCompleteFunc(this.func.callback);
else
setTimeout(() => this.onCompleteFunc(this.func.callback), this.func.ms);
}
}
export default WebAPIThreadPool;