Skip to content

Commit

Permalink
src: use lock for c-ares library init/cleanup
Browse files Browse the repository at this point in the history
This helps embedders wishing to use Node.js in a multi-threaded fashion
and helps pave the way for thread-based worker support.

Thanks to Stephen Belanger for reviewing this commit in its original PR.

Refs: ayojs/ayo#82

PR-URL: #20539
Reviewed-By: Tiancheng "Timothy" Gu <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Ben Noordhuis <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Daniel Bevenius <[email protected]>
  • Loading branch information
addaleax authored and targos committed May 12, 2018
1 parent 5803973 commit 2df99ac
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/cares_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ using v8::Value;

namespace {

Mutex ares_library_mutex;

inline uint16_t cares_get_16bit(const unsigned char* p) {
return static_cast<uint32_t>(p[0] << 8U) | (static_cast<uint32_t>(p[1]));
}
Expand Down Expand Up @@ -470,6 +472,7 @@ void ChannelWrap::Setup() {

int r;
if (!library_inited_) {
Mutex::ScopedLock lock(ares_library_mutex);
// Multiple calls to ares_library_init() increase a reference counter,
// so this is a no-op except for the first call to it.
r = ares_library_init(ARES_LIB_INIT_ALL);
Expand All @@ -483,6 +486,7 @@ void ChannelWrap::Setup() {
ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB);

if (r != ARES_SUCCESS) {
Mutex::ScopedLock lock(ares_library_mutex);
ares_library_cleanup();
return env()->ThrowError(ToErrorCodeString(r));
}
Expand All @@ -500,6 +504,7 @@ void ChannelWrap::Setup() {

ChannelWrap::~ChannelWrap() {
if (library_inited_) {
Mutex::ScopedLock lock(ares_library_mutex);
// This decreases the reference counter increased by ares_library_init().
ares_library_cleanup();
}
Expand Down

0 comments on commit 2df99ac

Please sign in to comment.