MvG
MvG

Reputation: 60968

Detect whether current thread is main thread of the libuv default event loop

I'm writing a piece of C code for Node.js and want to distinguish synchroneous from asynchroneous calls. In other words, I want to detect whether my code is running on the V8 event dispatch thread, called from within the main event loop, or whether it's called from some separate worker thread. In the former case, I could call back to JavaScript immediately, while in the latter I'd have to use a more complicated async callback.

The libuv threading API provides uv_thread_self to identify the current thread, and uv_thread_equal to compare threads for equality. So all I need is find the uv_thread_t of the main event loop.

Upvotes: 1

Views: 1507

Answers (2)

ekarak
ekarak

Reputation: 628

I suppose its as easy as grabbing the uv_thread_self() from the v8 thread in the module's initialisation (as you mentioned you use node.js)? This module init code is supposed to run from the main v8 thread, as this is require()'d from your library's Javascript package.

uv_thread_t main_thread;

extern "C" void init(Handle<Object> target, Handle<Object> module) {

    Nan::HandleScope scope;

    main_thread = uv_thread_self();

then you can use uv_thread_equal to determine whether the code is running in the main thread or not:

void ozw_watcher_callback(OpenZWave::Notification const *cb, void *ctx)
// ===================================================================
{
    uv_thread_t this_thread = uv_thread_self();
    std::cout << "~~~~ ozw_watcher_callback : main thread? " << (uv_thread_equal(&main_thread, &this_thread)) << "\n";

Upvotes: 1

Squirrel
Squirrel

Reputation: 2282

On Linux (and possibly MacOS and Solaris), you could have a look at backtrace():

backtrace() returns a backtrace for the calling program, in the array pointed to by buffer. A backtrace is the series of currently active function calls for the program.

and it's friend, backtrace_symbols():

Given the set of addresses returned by backtrace() in buffer, backtrace_symbols() translates the addresses into an array of strings that describe the addresses symbolically. The size argument specifies the number of addresses in buffer. The symbolic representation of each address consists of the function name (if this can be determined), a hexadecimal offset into the function, and the actual return address (in hexadecimal).

http://linux.die.net/man/3/backtrace

On Windows, I think the following question shows how to achieve similar functionality: http://bewitchingkitchen.com/2010/01/30/slow-roasted-chicken-thighs-an-ice-breaker/

Upvotes: 0

Related Questions