Skip to content

Commit 2b777c3

Browse files
RahulHereRahulHere
authored andcommitted
Improve libevent threading initialization order
Use static initializer to call evthread_use_pthreads() at program startup, before any other code (including curl) can initialize libevent. This fixes the "evthread initialization must be called BEFORE anything else!" error on systems where curl is compiled with libevent support. Changes: - Remove event_enable_debug_mode() which can only be called once and causes issues with shared libraries - Use simple static initializer instead of constructor priority attribute - evthread_use_pthreads() is safe to call multiple times
1 parent 26d08fa commit 2b777c3

1 file changed

Lines changed: 23 additions & 10 deletions

File tree

src/event/libevent_dispatcher.cc

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,22 +74,35 @@ uint32_t fromLibeventEvents(short events) {
7474
return result;
7575
}
7676

77-
// Lazy initialization for libevent threading support
78-
// Uses std::call_once to ensure thread-safe one-time initialization
79-
// This avoids blocking in static initialization which was causing hangs
80-
void ensureLibeventThreadingInitialized() {
81-
static std::once_flag init_flag;
82-
std::call_once(init_flag, []() {
77+
// Early initialization for libevent threading support
78+
// CRITICAL: This must run BEFORE any other libevent functions or libraries
79+
// that might use libevent (like curl with libevent support).
80+
// evthread_use_pthreads() is safe to call multiple times - it returns 0 after first call
81+
struct LibeventEarlyInit {
82+
LibeventEarlyInit() {
8383
#ifdef _WIN32
8484
evthread_use_windows_threads();
8585
#else
8686
evthread_use_pthreads();
8787
#endif
88-
// Enable debug mode in debug builds
89-
#ifndef NDEBUG
90-
event_enable_debug_mode();
88+
// NOTE: event_enable_debug_mode() is NOT called here because:
89+
// 1. It can only be called once across the entire process
90+
// 2. With shared libraries, this code may run from multiple TUs
91+
// 3. Debug mode is only needed for debugging libevent internals
92+
}
93+
};
94+
95+
// Single static instance ensures initialization at program startup
96+
static LibeventEarlyInit s_libevent_early_init;
97+
98+
// This function is kept for compatibility
99+
void ensureLibeventThreadingInitialized() {
100+
// evthread functions are safe to call multiple times
101+
#ifdef _WIN32
102+
evthread_use_windows_threads();
103+
#else
104+
evthread_use_pthreads();
91105
#endif
92-
});
93106
}
94107

95108
} // namespace

0 commit comments

Comments
 (0)