Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example: add TypedThreadSafeFunction #185

Merged
merged 3 commits into from
Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions typed_threadsafe_function/node-addon-api/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
project (clock)
include_directories(${CMAKE_JS_INC} node_modules/node-addon-api/)
cmake_minimum_required(VERSION 3.18)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(${CMAKE_JS_INC})
file(GLOB SOURCE_FILES "*.cc")
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})

# Include Node-API wrappers
execute_process(COMMAND node -p "require('node-addon-api').include"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE NODE_ADDON_API_DIR
)
string(REGEX REPLACE "[\r\n\"]" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})

target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})

# define NAPI_VERSION
add_definitions(-DNAPI_VERSION=4)
94 changes: 94 additions & 0 deletions typed_threadsafe_function/node-addon-api/clock.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#include <chrono>
#include <napi.h>
#include <thread>

using namespace Napi;

using Context = Reference<Value>;
using DataType = int;
void CallJs(Napi::Env env, Function callback, Context *context, DataType *data);
using TSFN = TypedThreadSafeFunction<Context, DataType, CallJs>;
using FinalizerDataType = void;

std::thread nativeThread;
TSFN tsfn;

Value Start(const CallbackInfo &info) {
Napi::Env env = info.Env();

if (info.Length() < 2) {
throw TypeError::New(env, "Expected two arguments");
} else if (!info[0].IsFunction()) {
throw TypeError::New(env, "Expected first arg to be function");
} else if (!info[1].IsNumber()) {
throw TypeError::New(env, "Expected second arg to be number");
}

int count = info[1].As<Number>().Int32Value();

// Create a new context set to the the receiver (ie, `this`) of the function
// call
Context *context = new Reference<Value>(Persistent(info.This()));

// Create a ThreadSafeFunction
tsfn = TSFN::New(
env,
info[0].As<Function>(), // JavaScript function called asynchronously
"Resource Name", // Name
0, // Unlimited queue
1, // Only one thread will use this initially
context,
[](Napi::Env, FinalizerDataType *,
Context *ctx) { // Finalizer used to clean threads up
nativeThread.join();
delete ctx;
});

// Create a native thread
nativeThread = std::thread([count] {
for (int i = 0; i < count; i++) {
// Create new data
int *value = new int(clock());

// Perform a blocking call
napi_status status = tsfn.BlockingCall(value);
if (status != napi_ok) {
// Handle error
break;
}

std::this_thread::sleep_for(std::chrono::seconds(1));
}

// Release the thread-safe function
tsfn.Release();
});

return Boolean::New(env, true);
}

// Transform native data into JS data, passing it to the provided
// `callback` -- the TSFN's JavaScript function.
void CallJs(Napi::Env env, Function callback, Context *context,
DataType *data) {
// Is the JavaScript environment still available to call into, eg. the TSFN is
// not aborted
if (env != nullptr) {
// On Node-API 5+, the `callback` parameter is optional; however, this example
// does ensure a callback is provided.
if (callback != nullptr) {
callback.Call(context->Value(), {Number::New(env, *data)});
}
}
if (data != nullptr) {
// We're finished with the data.
delete data;
}
}

Napi::Object Init(Napi::Env env, Object exports) {
exports.Set("start", Function::New(env, Start));
return exports;
}

NODE_API_MODULE(clock, Init)
6 changes: 6 additions & 0 deletions typed_threadsafe_function/node-addon-api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const { start } = require('bindings')('clock');

start.call(new Date(), function (clock) {
const context = this;
console.log(context, clock);
}, 5);
17 changes: 17 additions & 0 deletions typed_threadsafe_function/node-addon-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "example-typedthreadsafefunction",
"version": "0.0.0",
"description": "node-addon-api TypedThreadSafeFunction example",
"main": "index.js",
"private": true,
"dependencies": {
"bindings": "~1.2.1",
"cmake-js": "^6.1.0",
"node-addon-api": "^4.0.0"
},
"scripts": {
"test": "node index.js",
"install": "cmake-js compile"
},
"gypfile": true
}