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: https://github.com/ayojs/ayo/pull/82

PR-URL: https://github.com/nodejs/node/pull/20539
Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
This commit is contained in:
Anna Henningsen committed 2018-05-09 18:19:02 +02:00
1 parent 987387534a
commit ccdee34072
1 file changed
+5
+5
View File
@@ -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]));
}
@@ -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);
@@ -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));
}
@@ -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();
}