Skip to content

Commit 2df99ac

Browse files
addaleaxtargos
authored andcommitted
src: use lock for c-ares library init/cleanup
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]>
1 parent 5803973 commit 2df99ac

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

src/cares_wrap.cc

+5
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ using v8::Value;
7070

7171
namespace {
7272

73+
Mutex ares_library_mutex;
74+
7375
inline uint16_t cares_get_16bit(const unsigned char* p) {
7476
return static_cast<uint32_t>(p[0] << 8U) | (static_cast<uint32_t>(p[1]));
7577
}
@@ -470,6 +472,7 @@ void ChannelWrap::Setup() {
470472

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

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

501505
ChannelWrap::~ChannelWrap() {
502506
if (library_inited_) {
507+
Mutex::ScopedLock lock(ares_library_mutex);
503508
// This decreases the reference counter increased by ares_library_init().
504509
ares_library_cleanup();
505510
}

0 commit comments

Comments
 (0)