JavaScript 單線程事件循環機制無法阻塞主線程。常見的空循環 while(Date.now() - start < ms) 會佔用 100% CPU,並非真正的睡眠。
通過編寫 C++ Addon 直接調用系統 Sleep (Windows) 或 usleep/nanosleep (Linux/macOS),讓執行緒真正釋放 CPU 時間片。
npm install -g node-gypnpm init
# package.json 添加 "gyp-file": true
binding.gyp 示例:
{
"targets": [{
"target_name": "hello",
"sources": ["hello.cc"],
"include_dirs": ["
nan (Native Abstractions for Node.js) 提供統一 API,兼容 Node 0.8 至最新版本。
npm install --save nan
#include
using namespace v8;
NAN_METHOD(Sleep) {
NanScope();
double ms = args[0]->NumberValue();
Sleep(ms); // Windows: Sleep(ms); Linux: usleep(ms*1000);
NanReturnUndefined();
}
void Init(Handle
node-gyp configure
node-gyp build
# 生成 build/Release/hello.node
JS 調用:
var sleep = require('./build/Release/hello.node').sleep;
console.log(new Date());
sleep(1000); // 阻塞 1 秒,不佔用 CPU
console.log(new Date());