8000 Improve async pool · HowProgrammingWorks/Pool@bdd6712 · GitHub
[go: up one dir, main page]

Skip to content

Commit bdd6712

Browse files
committed
Improve async pool
1 parent 4ca0f82 commit bdd6712

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

JavaScript/5-async.js

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
11
'use strict';
22

3-
const poolify = (factory, min, norm, max) => {
4-
5-
const duplicate = n => new Array(n).fill().map(() => factory());
3+
const duplicate = (factory, n) => (
4+
new Array(n).fill().map(() => factory())
5+
);
66

7+
const poolify = (factory, min, norm, max) => {
8+
let allocated = norm;
79
const pool = (par) => {
810
if (typeof(par) !== 'function') {
911
if (pool.items.length < max) {
1012
const delayed = pool.delayed.pop();
1113
if (delayed) {
12-
console.log('Recycle item, pass to delayed');
14+
console.log('Recycle item, pass to delayed', pool.items.length);
1315
delayed(par);
14-
return;
1516
} else {
17+
console.log('Recycle item, add to pool', pool.items.length);
1618
pool.items.push(par);
1719
}
1820
}
19-
console.log('Recycle item, count =', pool.items.length);
2021
return;
2122
}
22-
if (pool.items.length < min) {
23-
const items = duplicate(norm - pool.items.length);
23+
if (pool.items.length < min && allocated < max) {
24+
const grow = Math.min(max - allocated, norm - pool.items.length);
25+
allocated += grow;
26+
const items = duplicate(factory, grow);
2427
pool.items.push(...items);
2528
}
2629
const res = pool.items.pop();
27-
console.log('Get from pool, count =', pool.items.length);
2830
if (res) {
31+
console.log('Get from pool, pass to callback', pool.items.length);
2932
par(res);
3033
} else {
34+
console.log('Get from pool, add callback to queue', pool.items.length);
3135
pool.delayed.push(par);
32-
console.log('Request delayed');
3336
}
34-
return pool;
3537
};
36-
3738
return Object.assign(pool, {
38-
items: duplicate(norm),
39+
items: duplicate(factory, norm),
3940
delayed: []
4041
});
41-
4242
};
4343

4444
// Usage
@@ -47,15 +47,14 @@ const poolify = (factory, min, norm, max) => {
4747
const buffer = () => new Uint32Array(128);
4848

4949
// Allocate pool of 10 buffers
50-
const pool = poolify(buffer, 0, 5, 10);
50+
const pool = poolify(buffer, 3, 5, 7);
5151

5252
let i = 0;
5353

5454
const next = () => {
5555
pool(item => {
56-
console.log('Buffer size', item.length * 32);
5756
i++;
58-
if (i < 10) {
57+
if (i < 20) {
5958
setTimeout(next, i * 10);
6059
setTimeout(() => pool(item), i * 100);
6160
}

0 commit comments

Comments
 (0)
0