本文主要是介绍nodejs 14.0.0源码分析之FixedQueue,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
FixedQueue是用来实现nextTick的。代码不多。
'use strict';const {Array,
} = primordials;const kSize = 2048;
const kMask = kSize - 1;const FixedCircularBuffer = class FixedCircularBuffer {constructor() {this.bottom = 0;this.top = 0;this.list = new Array(kSize);this.next = null;}isEmpty() {return this.top === this.bottom;}// 要判断回环isFull() {return ((this.top + 1) & kMask) === this.bottom;}push(data) {this.list[this.top] = data;this.top = (this.top + 1) & kMask;}// 移除一个元素,更新位置shift() {const nextItem = this.list[this.bottom];// 没有元素了,不需要更新位置if (nextItem === undefined)return null;this.list[this.bottom] = undefined;this.bottom = (this.bottom + 1) & kMask;return nextItem;}
};module.exports = class FixedQueue {constructor() {this.head = this.tail = new FixedCircularBuffer();}isEmpty() {return this.head.isEmpty();}push(data) {// 满了则申请一个新的,head指向新的,tail指向最开始的那个,即最旧的if (this.head.isFull()) {// Head is full: Creates a new queue, sets the old queue's `.next` to it,// and sets it as the new main queue.this.head = this.head.next = new FixedCircularBuffer();}this.head.push(data);}shift() {const tail = this.tail;const next = tail.shift();// 消费完一个FixedCircularBuffer了,下一个if (tail.isEmpty() && tail.next !== null) {// If there is another queue, it forms the new tail.this.tail = tail.next;}return next;}
};
这篇关于nodejs 14.0.0源码分析之FixedQueue的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!