Skip to content

Instantly share code, notes, and snippets.

@deepal
Created October 15, 2019 21:36
Show Gist options
  • Save deepal/bbb9f351385e671bfbd2e72358fd6efe to your computer and use it in GitHub Desktop.
Save deepal/bbb9f351385e671bfbd2e72358fd6efe to your computer and use it in GitHub Desktop.
Trigger worker run
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
Worker* w;
ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
Mutex::ScopedLock lock(w->mutex_);
// The object now owns the created thread and should not be garbage collected
// until that finishes.
w->ClearWeak();
w->env()->add_sub_worker_context(w);
w->stopped_ = false;
w->thread_joined_ = false;
w->on_thread_finished_.Install(w->env(), w, [](uv_async_t* handle) {
Worker* w_ = static_cast<Worker*>(handle->data);
CHECK(w_->is_stopped());
w_->parent_port_ = nullptr;
w_->JoinThread();
delete w_;
});
uv_thread_options_t thread_options;
thread_options.flags = UV_THREAD_HAS_STACK_SIZE;
thread_options.stack_size = kStackSize;
CHECK_EQ(uv_thread_create_ex(&w->tid_, &thread_options, [](void* arg) {
Worker* w = static_cast<Worker*>(arg);
const uintptr_t stack_top = reinterpret_cast<uintptr_t>(&arg);
// Leave a few kilobytes just to make sure we're within limits and have
// some space to do work in C++ land.
w->stack_base_ = stack_top - (kStackSize - kStackBufferSize);
w->Run();
Mutex::ScopedLock lock(w->mutex_);
w->on_thread_finished_.Stop();
}, static_cast<void*>(w)), 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment