Skip to content

Commit

Permalink
Revert "cpp runtime: Remove pthread dependency. (#4086)"
Browse files Browse the repository at this point in the history
This reverts commit 2073147.
  • Loading branch information
parrt committed Feb 19, 2023
1 parent 2073147 commit a156a06
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
7 changes: 7 additions & 0 deletions runtime/Cpp/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ file(GLOB libantlrcpp_SRC
add_library(antlr4_shared SHARED ${libantlrcpp_SRC})
add_library(antlr4_static STATIC ${libantlrcpp_SRC})

# Make sure to link against threads (pthreads) library in order to be able to
# make use of std::call_once in the code without producing runtime errors
# (see also https://github.com/antlr/antlr4/issues/3708 and/or https://stackoverflow.com/q/51584960).
find_package(Threads REQUIRED)
target_link_libraries(antlr4_shared Threads::Threads)
target_link_libraries(antlr4_static Threads::Threads)

if (ANTLR_BUILD_CPP_TESTS)
include(FetchContent)

Expand Down
20 changes: 12 additions & 8 deletions runtime/Cpp/runtime/src/internal/Synchronization.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,12 @@

#include "antlr4-common.h"

#include <atomic>
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <utility>

#if ANTLR4CPP_USING_ABSEIL
#include "absl/base/call_once.h"
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
#define ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS ABSL_NO_THREAD_SAFETY_ANALYSIS
Expand Down Expand Up @@ -136,15 +135,20 @@ namespace antlr4::internal {
template <typename Callable, typename... Args>
friend void call_once(OnceFlag &onceFlag, Callable &&callable, Args&&... args);

std::atomic_flag _flag = ATOMIC_FLAG_INIT;
#if ANTLR4CPP_USING_ABSEIL
absl::once_flag _impl;
#else
std::once_flag _impl;
#endif
};

template <typename Callable, typename... Args>
void call_once(OnceFlag &onceFlag, Callable &&callable, Args &&...args) {
if (onceFlag._flag.test_and_set()) {
return;
}
std::invoke(std::forward<Callable>(callable), std::forward<Args>(args)...);
void call_once(OnceFlag &onceFlag, Callable &&callable, Args&&... args) {
#if ANTLR4CPP_USING_ABSEIL
absl::call_once(onceFlag._impl, std::forward<Callable>(callable), std::forward<Args>(args)...);
#else
std::call_once(onceFlag._impl, std::forward<Callable>(callable), std::forward<Args>(args)...);
#endif
}

} // namespace antlr4::internal

0 comments on commit a156a06

Please sign in to comment.