node thread.sleep實現

最近在寫一些奇怪的東西的時候,發現大佬們用go或者其餘語言實現的併發任務用了thread.sleep讓主進程暫停。node

回頭一想,媽個雞我要複製粘貼到node一直循環不合適啊,我也須要暫停來着!npm

怎麼辦??併發

抓了腦殼一會去npm上找了下相關的包,發現有個叫thread-sleep的包,下載量還挺高。app

抱着好奇心去看了下源碼,又發現源碼至關之騷氣oop

'use strict';

var childProcess = require('child_process');
var nodeBin = process.argv[0];

module.exports = sleep;
function sleep(milliseconds) {
  var start = Date.now();
  if (milliseconds !== Math.floor(milliseconds)) {
    throw new TypeError('sleep only accepts an integer number of milliseconds');
  } else if (milliseconds < 0) {
    throw new RangeError('sleep only accepts a positive number of milliseconds');
  } else if (milliseconds !== (milliseconds | 0)) {
    throw new RangeError('sleep duration out of range')
  }
  milliseconds = milliseconds | 0;

  var shouldEnd = start + milliseconds;
  try {
    childProcess.execFileSync(nodeBin, [ '-e',
      'setTimeout(function() {}, ' + shouldEnd + ' - Date.now());'
    ], {
      timeout: milliseconds,
    });
  } catch (ex) {
    if (ex.code !== 'ETIMEDOUT') {
      throw ex;
    }
  }
  var end = Date.now();
  return end - start;
}

黑人問號???ui

這是什麼奇怪的實現。spa

翻閱node文檔發現code

Synchronous Process Creation#

The child_process.spawnSync(), 
child_process.execSync(), and child_process.execFileSync() methods are synchronous and WILL block the Node.js event loop, 
pausing execution of any additional code until the spawned process exits.

Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup.

???進程

以上三種同步方法會阻塞nodejs的事件循環,除非建立的子進程執行完了,纔會繼續執行下面的代碼。事件

thread-sleep包的做者正是利用這一特性實現了sleep功能。歎爲觀止

圖片描述

因此不少時候咱們沒辦法解決現有問題的緣由是對文檔不熟麼??

相關文章
相關標籤/搜索