From de0ed5fc3d9f7702f0d4426eb6aa4169d15e1ec6 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 21 Apr 2023 18:15:56 +0100 Subject: [PATCH 01/79] Option to disable threading in arrow This is useful for emscripten, where a lot of the time one doesn't have any threads. Could also be useful for any embedded ports etc. --- cpp/CMakeLists.txt | 13 +- cpp/cmake_modules/ThirdpartyToolchain.cmake | 65 ++++--- cpp/src/arrow/util/config.h.cmake | 1 + cpp/src/arrow/util/thread_pool.cc | 194 +++++++++++++++++++- cpp/src/arrow/util/thread_pool.h | 81 +++++++- 5 files changed, 319 insertions(+), 35 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index ac7067c0d6cf..aba49e1118ec 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -370,6 +370,10 @@ if(ARROW_ENABLE_TIMING_TESTS) add_definitions(-DARROW_WITH_TIMING_TESTS) endif() +if(ARROW_DISABLE_THREADING) + add_definitions(-DARROW_DISABLE_THREADING) +endif() + if(NOT ARROW_BUILD_BENCHMARKS) set(NO_BENCHMARKS 1) else() @@ -910,10 +914,11 @@ endif() # Handle platform-related libraries like -pthread set(ARROW_SYSTEM_LINK_LIBS) - -list(APPEND ARROW_SYSTEM_LINK_LIBS Threads::Threads) -if(CMAKE_THREAD_LIBS_INIT) - string(APPEND ARROW_PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") +if(!ARROW_DISABLE_THREADING) + list(APPEND ARROW_SYSTEM_LINK_LIBS Threads::Threads) + if(CMAKE_THREAD_LIBS_INIT) + string(APPEND ARROW_PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") + endif() endif() if(WIN32) diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake index 8bd02a867281..514b321fa3ca 100644 --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -942,9 +942,13 @@ endif() # ---------------------------------------------------------------------- # Find pthreads -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_package(Threads REQUIRED) - +if (!ARROW_DISABLE_THREADING) + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) + set(THREADS_LINK_LIB Threads::Threads) +else() + set(THREADS_LINK_LIB "") +endif() # ---------------------------------------------------------------------- # Add Boost dependencies (code adapted from Apache Kudu) @@ -2001,11 +2005,18 @@ macro(build_jemalloc) # The include directory must exist before it is referenced by a target. file(MAKE_DIRECTORY "${JEMALLOC_INCLUDE_DIR}") add_library(jemalloc::jemalloc STATIC IMPORTED) - set_target_properties(jemalloc::jemalloc - PROPERTIES INTERFACE_LINK_LIBRARIES Threads::Threads - IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${JEMALLOC_INCLUDE_DIR}") + if (ARROW_DISABLE_THREADING) + set_target_properties(jemalloc::jemalloc + PROPERTIES IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${JEMALLOC_INCLUDE_DIR}") + else() + set_target_properties(jemalloc::jemalloc + PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} + IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${JEMALLOC_INCLUDE_DIR}") + endif() add_dependencies(jemalloc::jemalloc jemalloc_ep) list(APPEND ARROW_BUNDLED_STATIC_LIBS jemalloc::jemalloc) @@ -2060,10 +2071,10 @@ if(ARROW_MIMALLOC) add_library(mimalloc::mimalloc STATIC IMPORTED) set_target_properties(mimalloc::mimalloc - PROPERTIES INTERFACE_LINK_LIBRARIES Threads::Threads - IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${MIMALLOC_INCLUDE_DIR}") + PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} + IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${MIMALLOC_INCLUDE_DIR}") if(WIN32) set_property(TARGET mimalloc::mimalloc APPEND @@ -4006,7 +4017,9 @@ macro(build_grpc) c-ares::cares ZLIB::ZLIB OpenSSL::SSL - Threads::Threads) + ${THREADS_LINK_LIB} + ) + set_target_properties(gRPC::grpc PROPERTIES IMPORTED_LOCATION "${GRPC_STATIC_LIBRARY_GRPC}" INTERFACE_INCLUDE_DIRECTORIES "${GRPC_INCLUDE_DIR}" @@ -4280,15 +4293,17 @@ macro(build_google_cloud_cpp_storage) # Version 1.39.0 is at a different place (they refactored after): # https://github.com/googleapis/google-cloud-cpp/blob/29e5af8ca9b26cec62106d189b50549f4dc1c598/google/cloud/CMakeLists.txt#L146-L155 set_property(TARGET google-cloud-cpp::common - PROPERTY INTERFACE_LINK_LIBRARIES - absl::base - absl::memory - absl::optional - absl::span - absl::time - absl::variant - Threads::Threads - OpenSSL::Crypto) + PROPERTY INTERFACE_LINK_LIBRARIES + absl::base + absl::memory + absl::optional + absl::span + absl::time + absl::variant + ${THREADS_LINK_LIB} + OpenSSL::Crypto) + + add_library(google-cloud-cpp::rest-internal STATIC IMPORTED) set_target_properties(google-cloud-cpp::rest-internal @@ -4324,7 +4339,7 @@ macro(build_google_cloud_cpp_storage) nlohmann_json::nlohmann_json Crc32c::crc32c CURL::libcurl - Threads::Threads + ${THREADS_LINK_LIB} OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB) @@ -4470,7 +4485,7 @@ macro(build_orc) set(ORC_LINK_LIBRARIES LZ4::lz4 ZLIB::ZLIB ${ARROW_ZSTD_LIBZSTD} ${Snappy_TARGET}) if(NOT MSVC) if(NOT APPLE) - list(APPEND ORC_LINK_LIBRARIES Threads::Threads) + list(APPEND ORC_LINK_LIBRARIES ${THREADS_LINK_LIB}) endif() list(APPEND ORC_LINK_LIBRARIES ${CMAKE_DL_LIBS}) endif() @@ -4653,7 +4668,7 @@ macro(build_opentelemetry) set_target_properties(opentelemetry-cpp::common PROPERTIES INTERFACE_LINK_LIBRARIES - "opentelemetry-cpp::api;opentelemetry-cpp::sdk;Threads::Threads" + "opentelemetry-cpp::api;opentelemetry-cpp::sdk;" ${THREADS_LINK_LIB} ) set_target_properties(opentelemetry-cpp::resources PROPERTIES INTERFACE_LINK_LIBRARIES "opentelemetry-cpp::common") diff --git a/cpp/src/arrow/util/config.h.cmake b/cpp/src/arrow/util/config.h.cmake index f6fad2016a27..0b194f32dd1f 100644 --- a/cpp/src/arrow/util/config.h.cmake +++ b/cpp/src/arrow/util/config.h.cmake @@ -57,5 +57,6 @@ #cmakedefine ARROW_WITH_MUSL #cmakedefine ARROW_WITH_OPENTELEMETRY #cmakedefine ARROW_WITH_UCX +#cmakedefine ARROW_DISABLE_THREADING #cmakedefine GRPCPP_PP_INCLUDE diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index daffe8f077a2..448569c1e1eb 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -62,9 +62,22 @@ struct SerialExecutor::State { bool finished{false}; }; -SerialExecutor::SerialExecutor() : state_(std::make_shared()) {} +#ifdef ARROW_DISABLE_THREADING +// list of all SerialExecutor objects - as we need to run tasks from all pools at once in Run() +std::unordered_set SerialExecutor::all_executors; +#endif + +SerialExecutor::SerialExecutor() : state_(std::make_shared()) +{ +#ifdef ARROW_DISABLE_THREADING + all_executors.insert(this); +#endif +} SerialExecutor::~SerialExecutor() { +#ifdef ARROW_DISABLE_THREADING + all_executors.erase(this); +#endif auto state = state_; std::unique_lock lk(state->mutex); if (!state->task_queue.empty()) { @@ -77,6 +90,38 @@ SerialExecutor::~SerialExecutor() { } } +int SerialExecutor::GetNumTasks() +{ + auto state = state_; + return state_->task_queue.size(); +} + +#ifdef ARROW_DISABLE_THREADING +Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, + StopToken stop_token, StopCallback&& stop_callback) { +#ifdef ARROW_WITH_OPENTELEMETRY + // Wrap the task to propagate a parent tracing span to it + // XXX should there be a generic utility in tracing_internal.h for this? + task = [func = std::move(task), + active_span = + ::arrow::internal::tracing::GetTracer()->GetCurrentSpan()]() mutable { + auto scope = ::arrow::internal::tracing::GetTracer()->WithActiveSpan(active_span); + std::move(func)(); + }; +#endif// ARROW_WITH_OPENTELEMETRY + + if (state_->finished) { + return Status::Invalid( + "Attempt to schedule a task on a serial executor that has already finished or " + "been abandoned"); + } + + state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); + SerialExecutor::RunTasksOnAllExecutors(); + return Status::OK(); +} + +#else //ARROW_DISABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { #ifdef ARROW_WITH_OPENTELEMETRY @@ -110,7 +155,7 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, state->wait_for_tasks.notify_one(); return Status::OK(); } - +#endif void SerialExecutor::Pause() { // Same comment as SpawnReal above auto state = state_; @@ -147,6 +192,98 @@ bool SerialExecutor::OwnsThisThread() { std::lock_guard lk(state_->mutex); return std::this_thread::get_id() == state_->current_thread; } +#if ARROW_DISABLE_THREADING + +void SerialExecutor::RunTasksOnAllExecutors() +{ + bool run_task=true; + while(run_task) + { + run_task=false; + for(auto it=all_executors.begin();it!=all_executors.end();it++) + { + SerialExecutor* exe = *it; + if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) + { + Task task = std::move(exe->state_->task_queue.front()); + exe->state_->task_queue.pop_front(); + run_task=true; + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); + } + } + } + } + } +} + +// run tasks in this thread and queue things from other executors if required +// (e.g. when a compute task depends on an IO request) +void SerialExecutor::RunLoop() +{ + // If paused we break out immediately. If finished we only break out + // when all work is done. + while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { + + // The inner loop is to check if we need to sleep (e.g. while waiting on some + // async task to finish from another thread pool). We still need to check paused + // because sometimes we will pause even with work leftover when processing + // an async generator + while (!state_->paused && !state_->task_queue.empty()) { + Task task = std::move(state_->task_queue.front()); + state_->task_queue.pop_front(); + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); + } + // Can't break here because there may be cleanup tasks down the chain we still + // need to run. + } + } + // In this case we must be waiting on work from external (e.g. I/O) executors. Run things + // in all serialexecutors until we have something in queue + + int executor_pos=0; + while ((state_->paused || state_->task_queue.empty() ) && !state_->finished) + { + // we cycle round executors in turn, in case e.g. we are reading multiple + // file inputs or something like that + // n.b. we don't do this with an iterator because + // these calls may delete or add executors + int count=(executor_pos)%all_executors.size(); + for(auto it=all_executors.begin();it!=all_executors.end();it++) + { + if (count==0) + { + // run a single task from this executor if it isn't paused + SerialExecutor* exe = *it; + if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) + { + Task task = std::move(exe->state_->task_queue.front()); + exe->state_->task_queue.pop_front(); + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); + } + } + } + break; + } + count-=1; + } + executor_pos+=1; + } + } +} + +#else //ARROW_DISABLE_THREADING void SerialExecutor::RunLoop() { // This is called from the SerialExecutor's main thread, so the @@ -173,16 +310,65 @@ void SerialExecutor::RunLoop() { // Can't break here because there may be cleanup tasks down the chain we still // need to run. } - lk.lock(); } // In this case we must be waiting on work from external (e.g. I/O) executors. Wait // for tasks to arrive (typically via transferred futures). state_->wait_for_tasks.wait(lk, [&] { return state_->paused || state_->finished || !state_->task_queue.empty(); }); + } state_->current_thread = {}; } +#endif //ARROW_DISABLE_THREADING + +#if ARROW_DISABLE_THREADING + +ThreadPool::ThreadPool() +{ + +} + +Status ThreadPool::Shutdown(bool wait) +{ + if(wait) + { + RunLoop(); + } + return Status::OK(); +} + +// Wait for the 'thread pool' to become idle +// including running tasks from other pools if +// needed +void ThreadPool::WaitForIdle() +{ + while(!state_->task_queue.empty()) + { + RunLoop(); + } +} + +Result> ThreadPool::Make(int threads) { + auto pool = std::shared_ptr(new ThreadPool()); + RETURN_NOT_OK(pool->SetCapacity(threads)); + return pool; +} + +Result> ThreadPool::MakeEternal(int threads) { + ARROW_ASSIGN_OR_RAISE(auto pool, Make(threads)); + // On Windows, the ThreadPool destructor may be called after non-main threads + // have been killed by the OS, and hang in a condition variable. + // On Unix, we want to avoid leak reports by Valgrind. + return pool; +} + +ThreadPool::~ThreadPool() +{ + // NOP +} + +#else // ARROW_DISABLE_THREADING struct ThreadPool::State { State() = default; @@ -532,6 +718,8 @@ int ThreadPool::DefaultCapacity() { return capacity; } +#endif //ARROW_DISABLE_THREADING + // Helper for the singleton pattern std::shared_ptr ThreadPool::MakeCpuThreadPool() { auto maybe_pool = ThreadPool::MakeEternal(ThreadPool::DefaultCapacity()); diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 4e0fd84068c9..e1ec42dcd2ea 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -22,6 +22,7 @@ #include #include #include +#include #include "arrow/result.h" #include "arrow/status.h" @@ -276,6 +277,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { Status SpawnReal(TaskHints hints, FnOnce task, StopToken, StopCallback&&) override; + // Return the number of tasks either running or in the queue. + int GetNumTasks(); + + /// \brief Runs the TopLevelTask and any scheduled tasks /// /// The TopLevelTask (or one of the tasks it schedules) must either return an invalid @@ -367,14 +372,16 @@ class ARROW_EXPORT SerialExecutor : public Executor { return Iterator(SerialIterator{std::move(serial_executor), std::move(generator)}); } - private: - SerialExecutor(); +protected: + virtual void RunLoop(); // State uses mutex struct State; std::shared_ptr state_; - void RunLoop(); + SerialExecutor(); + + // We mark the serial executor "finished" when there should be // no more tasks scheduled on it. It's not strictly needed but // can help catch bugs where we are trying to use the executor @@ -393,8 +400,75 @@ class ARROW_EXPORT SerialExecutor : public Executor { RunLoop(); return final_fut; } + +#ifdef ARROW_DISABLE_THREADING + // we have to run tasks from all live executors + // during RunLoop if we don't have threading + static std::unordered_set all_executors; + static void RunTasksOnAllExecutors(); // run loop until everything works okay + +#endif // ARROW_DISABLE_THREADING + +}; + +#ifdef ARROW_DISABLE_THREADING +// an executor implementation which pretends to be a thread pool but runs everything +// on the main thread using a static queue (shared between all thread pools, otherwise +// cross-threadpool dependencies will break everything) +class ARROW_EXPORT ThreadPool : public SerialExecutor +{ + public: + + ARROW_FRIEND_EXPORT friend ThreadPool* GetCpuThreadPool(); + + + static Result> Make(int threads); + + // Like Make(), but takes care that the returned ThreadPool is compatible + // with destruction late at process exit. + static Result> MakeEternal(int threads); + + // Destroy thread pool; the pool will first be shut down + ~ThreadPool() override; + + // Return the desired number of worker threads. + // The actual number of workers may lag a bit before being adjusted to + // match this value. + int GetCapacity() override + { + return 1; + } + + bool OwnsThisThread() override + { + return true; + } + + // Dynamically change the number of worker threads. + // - no op when threading is disabled + Status SetCapacity(int threads){return Status::OK();} + + static int DefaultCapacity(){return 1;} + + // Shutdown the pool. Once the pool starts shutting down, new tasks + // cannot be submitted anymore. + // If "wait" is true, shutdown waits for all pending tasks to be finished. + // If "wait" is false, workers are stopped as soon as currently executing + // tasks are finished. + Status Shutdown(bool wait = true); + + // Wait for the thread pool to become idle + // + // This is useful for sequencing tests + void WaitForIdle(); + protected: + static std::shared_ptr MakeCpuThreadPool(); + ThreadPool(); + }; +#else // ARROW_DISABLE_THREADING + /// An Executor implementation spawning tasks in FIFO manner on a fixed-size /// pool of worker threads. /// @@ -475,6 +549,7 @@ class ARROW_EXPORT ThreadPool : public Executor { State* state_; bool shutdown_on_destroy_; }; +#endif // ARROW_DISABLE_THREADING // Return the process-global thread pool for CPU-bound tasks. ARROW_EXPORT ThreadPool* GetCpuThreadPool(); From 1c62fc1371f9d3bad5301a33db1752c4530d57c1 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 22 Apr 2023 08:29:28 +0100 Subject: [PATCH 02/79] added threading disable to CI build script --- ci/scripts/cpp_build.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/ci/scripts/cpp_build.sh b/ci/scripts/cpp_build.sh index abeb65404759..7fa840de18b2 100755 --- a/ci/scripts/cpp_build.sh +++ b/ci/scripts/cpp_build.sh @@ -128,6 +128,7 @@ cmake \ -DARROW_WITH_UTF8PROC=${ARROW_WITH_UTF8PROC:-ON} \ -DARROW_WITH_ZLIB=${ARROW_WITH_ZLIB:-OFF} \ -DARROW_WITH_ZSTD=${ARROW_WITH_ZSTD:-OFF} \ + -DARROW_DISABLE_THREADING=${ARROW_DISABLE_THREADING:-OFF} \ -DAWSSDK_SOURCE=${AWSSDK_SOURCE:-} \ -Dbenchmark_SOURCE=${benchmark_SOURCE:-} \ -DBOOST_SOURCE=${BOOST_SOURCE:-} \ From 872d317a74c7cfc305a212375092a7c93b501301 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 22 Apr 2023 08:35:13 +0100 Subject: [PATCH 03/79] disable threading test in github actions --- .github/workflows/cpp.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index b5631ca3bd82..4bab042f2cd6 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -83,11 +83,20 @@ jobs: runs-on: ["self-hosted", "arm", "linux"] title: ARM64 Ubuntu 20.04 C++ ubuntu: "20.04" + - arch: amd64 + clang-tools: "14" + image: conda-cpp + llvm: "14" + runs-on: ubuntu-latest + title: AMD64 Conda C++ no threads + ubuntu: "22.04" + disable_threading: "ON" env: ARCH: ${{ matrix.arch }} CLANG_TOOLS: ${{ matrix.clang-tools }} LLVM: ${{ matrix.llvm }} UBUNTU: ${{ matrix.ubuntu }} + ARROW_DISABLE_THREADING: ${{matrix.disable_threading}} steps: - name: Checkout Arrow uses: actions/checkout@v3 From 4507c312ad564774b3037fdfd37043e44de62564 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 22 Apr 2023 08:49:28 +0100 Subject: [PATCH 04/79] hopefully fixed thread library errors in cmake on CI --- cpp/cmake_modules/ThirdpartyToolchain.cmake | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake index 7dddb795c883..7bed6ec2231e 100644 --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -2013,7 +2013,7 @@ macro(build_jemalloc) # The include directory must exist before it is referenced by a target. file(MAKE_DIRECTORY "${JEMALLOC_INCLUDE_DIR}") add_library(jemalloc::jemalloc STATIC IMPORTED) - if (ARROW_DISABLE_THREADING) + if ("${THREADS_LINK_LIB}" STREQUAL "") set_target_properties(jemalloc::jemalloc PROPERTIES IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" INTERFACE_INCLUDE_DIRECTORIES @@ -2078,11 +2078,18 @@ if(ARROW_MIMALLOC) file(MAKE_DIRECTORY ${MIMALLOC_INCLUDE_DIR}) add_library(mimalloc::mimalloc STATIC IMPORTED) - set_target_properties(mimalloc::mimalloc - PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} - IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${MIMALLOC_INCLUDE_DIR}") + if ("${THREADS_LINK_LIB}" STREQUAL "") + set_target_properties(mimalloc::mimalloc + PROPERTIES IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${MIMALLOC_INCLUDE_DIR}") + else() + set_target_properties(mimalloc::mimalloc + PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} + IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${MIMALLOC_INCLUDE_DIR}") + endif() if(WIN32) set_property(TARGET mimalloc::mimalloc APPEND From 91b9ce356cfbe8b968fa4cb75fa02b81a5d4a443 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 22 Apr 2023 15:13:21 +0100 Subject: [PATCH 05/79] tying to get threading flag passed through correctly --- .github/workflows/cpp.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index 4bab042f2cd6..bb24d835e9ea 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -62,6 +62,14 @@ jobs: fail-fast: false matrix: include: + - arch: amd64 + clang-tools: "14" + image: conda-cpp + llvm: "14" + runs-on: ubuntu-latest + title: AMD64 Conda C++ no threads + ubuntu: "22.04" + disable_threading: "ON" - arch: amd64 clang-tools: "14" image: conda-cpp @@ -83,14 +91,6 @@ jobs: runs-on: ["self-hosted", "arm", "linux"] title: ARM64 Ubuntu 20.04 C++ ubuntu: "20.04" - - arch: amd64 - clang-tools: "14" - image: conda-cpp - llvm: "14" - runs-on: ubuntu-latest - title: AMD64 Conda C++ no threads - ubuntu: "22.04" - disable_threading: "ON" env: ARCH: ${{ matrix.arch }} CLANG_TOOLS: ${{ matrix.clang-tools }} @@ -121,7 +121,7 @@ jobs: run: | sudo sysctl -w kernel.core_pattern="core.%e.%p" ulimit -c unlimited - archery docker run ${{ matrix.image }} + archery docker run --env ${ARROW_DISABLE_THREADING:-NO} - name: Docker Push if: success() && github.event_name == 'push' && github.repository == 'apache/arrow' env: From e9d912fbda746fc023e126cd3be7bac9c66cc15a Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 22 Apr 2023 15:18:36 +0100 Subject: [PATCH 06/79] fix to docker launch command --- .github/workflows/cpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index bb24d835e9ea..a506e57f422c 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -121,7 +121,7 @@ jobs: run: | sudo sysctl -w kernel.core_pattern="core.%e.%p" ulimit -c unlimited - archery docker run --env ${ARROW_DISABLE_THREADING:-NO} + archery docker run --env ARROW_DISABLE_THREADING=${ARROW_DISABLE_THREADING:-NO} ${{ matrix.image }} - name: Docker Push if: success() && github.event_name == 'push' && github.repository == 'apache/arrow' env: From 3c8421dea989b8caea2c0105373f6c712e41fcba Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 23 Apr 2023 14:06:58 +0100 Subject: [PATCH 07/79] removed define that goes into config.h --- cpp/CMakeLists.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index aba49e1118ec..7bd97a1168e9 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -370,9 +370,6 @@ if(ARROW_ENABLE_TIMING_TESTS) add_definitions(-DARROW_WITH_TIMING_TESTS) endif() -if(ARROW_DISABLE_THREADING) - add_definitions(-DARROW_DISABLE_THREADING) -endif() if(NOT ARROW_BUILD_BENCHMARKS) set(NO_BENCHMARKS 1) From a8e8e1a3482ead8d8888fb3b1988d21805a26562 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 24 Apr 2023 20:31:21 +0100 Subject: [PATCH 08/79] added explicit include of config.h --- cpp/src/arrow/util/thread_pool.h | 1 + 1 file changed, 1 insertion(+) diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index e1ec42dcd2ea..3f4bb0333828 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -24,6 +24,7 @@ #include #include +#include "arrow/util/config.h" #include "arrow/result.h" #include "arrow/status.h" #include "arrow/util/cancel.h" From 1260f51e5c9ed144a6abedf79ad877e27b5f3ba8 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 24 Apr 2023 21:06:08 +0100 Subject: [PATCH 09/79] typo fix --- ci/scripts/cpp_build.sh | 2 ++ cpp/src/arrow/util/thread_pool.cc | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ci/scripts/cpp_build.sh b/ci/scripts/cpp_build.sh index 7fa840de18b2..d3215b4c5265 100755 --- a/ci/scripts/cpp_build.sh +++ b/ci/scripts/cpp_build.sh @@ -164,6 +164,8 @@ cmake \ ${CMAKE_ARGS} \ ${source_dir} +cat src/arrow/utils.config.h + export CMAKE_BUILD_PARALLEL_LEVEL=${CMAKE_BUILD_PARALLEL_LEVEL:-$[${n_jobs} + 1]} time cmake --build . --target install diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 448569c1e1eb..b10aa03af9f4 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -192,7 +192,7 @@ bool SerialExecutor::OwnsThisThread() { std::lock_guard lk(state_->mutex); return std::this_thread::get_id() == state_->current_thread; } -#if ARROW_DISABLE_THREADING +#ifdef ARROW_DISABLE_THREADING void SerialExecutor::RunTasksOnAllExecutors() { @@ -322,7 +322,7 @@ void SerialExecutor::RunLoop() { } #endif //ARROW_DISABLE_THREADING -#if ARROW_DISABLE_THREADING +#ifdef ARROW_DISABLE_THREADING ThreadPool::ThreadPool() { From 10b8b1a3099f1c6fcebe44caa882f303a3cb0457 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 24 Apr 2023 22:18:59 +0100 Subject: [PATCH 10/79] removed debug out --- ci/scripts/cpp_build.sh | 2 -- 1 file changed, 2 deletions(-) diff --git a/ci/scripts/cpp_build.sh b/ci/scripts/cpp_build.sh index d3215b4c5265..7fa840de18b2 100755 --- a/ci/scripts/cpp_build.sh +++ b/ci/scripts/cpp_build.sh @@ -164,8 +164,6 @@ cmake \ ${CMAKE_ARGS} \ ${source_dir} -cat src/arrow/utils.config.h - export CMAKE_BUILD_PARALLEL_LEVEL=${CMAKE_BUILD_PARALLEL_LEVEL:-$[${n_jobs} + 1]} time cmake --build . --target install From 671296273ea3db739a49bbc1f98aa4325f08efad Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 24 Apr 2023 22:33:56 +0100 Subject: [PATCH 11/79] reverted thirdpartytoolchain --- cpp/cmake_modules/ThirdpartyToolchain.cmake | 76 ++++++++------------- 1 file changed, 27 insertions(+), 49 deletions(-) diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake index 2851566b7b05..0ab6d4668759 100644 --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -950,13 +950,9 @@ endif() # ---------------------------------------------------------------------- # Find pthreads -if (!ARROW_DISABLE_THREADING) - set(THREADS_PREFER_PTHREAD_FLAG ON) - find_package(Threads REQUIRED) - set(THREADS_LINK_LIB Threads::Threads) -else() - set(THREADS_LINK_LIB "") -endif() +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) + # ---------------------------------------------------------------------- # Add Boost dependencies (code adapted from Apache Kudu) @@ -2013,18 +2009,11 @@ macro(build_jemalloc) # The include directory must exist before it is referenced by a target. file(MAKE_DIRECTORY "${JEMALLOC_INCLUDE_DIR}") add_library(jemalloc::jemalloc STATIC IMPORTED) - if ("${THREADS_LINK_LIB}" STREQUAL "") - set_target_properties(jemalloc::jemalloc - PROPERTIES IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${JEMALLOC_INCLUDE_DIR}") - else() - set_target_properties(jemalloc::jemalloc - PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} - IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${JEMALLOC_INCLUDE_DIR}") - endif() + set_target_properties(jemalloc::jemalloc + PROPERTIES INTERFACE_LINK_LIBRARIES Threads::Threads + IMPORTED_LOCATION "${JEMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${JEMALLOC_INCLUDE_DIR}") add_dependencies(jemalloc::jemalloc jemalloc_ep) list(APPEND ARROW_BUNDLED_STATIC_LIBS jemalloc::jemalloc) @@ -2078,18 +2067,11 @@ if(ARROW_MIMALLOC) file(MAKE_DIRECTORY ${MIMALLOC_INCLUDE_DIR}) add_library(mimalloc::mimalloc STATIC IMPORTED) - if ("${THREADS_LINK_LIB}" STREQUAL "") - set_target_properties(mimalloc::mimalloc - PROPERTIES IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${MIMALLOC_INCLUDE_DIR}") - else() - set_target_properties(mimalloc::mimalloc - PROPERTIES INTERFACE_LINK_LIBRARIES ${THREADS_LINK_LIB} - IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" - INTERFACE_INCLUDE_DIRECTORIES - "${MIMALLOC_INCLUDE_DIR}") - endif() + set_target_properties(mimalloc::mimalloc + PROPERTIES INTERFACE_LINK_LIBRARIES Threads::Threads + IMPORTED_LOCATION "${MIMALLOC_STATIC_LIB}" + INTERFACE_INCLUDE_DIRECTORIES + "${MIMALLOC_INCLUDE_DIR}") if(WIN32) set_property(TARGET mimalloc::mimalloc APPEND @@ -4035,9 +4017,7 @@ macro(build_grpc) c-ares::cares ZLIB::ZLIB OpenSSL::SSL - ${THREADS_LINK_LIB} - ) - + Threads::Threads) set_target_properties(gRPC::grpc PROPERTIES IMPORTED_LOCATION "${GRPC_STATIC_LIBRARY_GRPC}" INTERFACE_INCLUDE_DIRECTORIES "${GRPC_INCLUDE_DIR}" @@ -4311,17 +4291,15 @@ macro(build_google_cloud_cpp_storage) # Version 1.39.0 is at a different place (they refactored after): # https://github.com/googleapis/google-cloud-cpp/blob/29e5af8ca9b26cec62106d189b50549f4dc1c598/google/cloud/CMakeLists.txt#L146-L155 set_property(TARGET google-cloud-cpp::common - PROPERTY INTERFACE_LINK_LIBRARIES - absl::base - absl::memory - absl::optional - absl::span - absl::time - absl::variant - ${THREADS_LINK_LIB} - OpenSSL::Crypto) - - + PROPERTY INTERFACE_LINK_LIBRARIES + absl::base + absl::memory + absl::optional + absl::span + absl::time + absl::variant + Threads::Threads + OpenSSL::Crypto) add_library(google-cloud-cpp::rest-internal STATIC IMPORTED) set_target_properties(google-cloud-cpp::rest-internal @@ -4357,7 +4335,7 @@ macro(build_google_cloud_cpp_storage) nlohmann_json::nlohmann_json Crc32c::crc32c CURL::libcurl - ${THREADS_LINK_LIB} + Threads::Threads OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB) @@ -4503,7 +4481,7 @@ macro(build_orc) set(ORC_LINK_LIBRARIES LZ4::lz4 ZLIB::ZLIB ${ARROW_ZSTD_LIBZSTD} ${Snappy_TARGET}) if(NOT MSVC) if(NOT APPLE) - list(APPEND ORC_LINK_LIBRARIES ${THREADS_LINK_LIB}) + list(APPEND ORC_LINK_LIBRARIES Threads::Threads) endif() list(APPEND ORC_LINK_LIBRARIES ${CMAKE_DL_LIBS}) endif() @@ -4686,7 +4664,7 @@ macro(build_opentelemetry) set_target_properties(opentelemetry-cpp::common PROPERTIES INTERFACE_LINK_LIBRARIES - "opentelemetry-cpp::api;opentelemetry-cpp::sdk;" ${THREADS_LINK_LIB} + "opentelemetry-cpp::api;opentelemetry-cpp::sdk;Threads::Threads" ) set_target_properties(opentelemetry-cpp::resources PROPERTIES INTERFACE_LINK_LIBRARIES "opentelemetry-cpp::common") @@ -5212,4 +5190,4 @@ message(STATUS "All bundled static libraries: ${ARROW_BUNDLED_STATIC_LIBS}") configure_file("src/arrow/util/config.h.cmake" "src/arrow/util/config.h" ESCAPE_QUOTES) install(FILES "${ARROW_BINARY_DIR}/src/arrow/util/config.h" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/arrow/util") + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/arrow/util") \ No newline at end of file From 4bf128e89f6f976e1074a2a78d08b6c69f40216d Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 26 Apr 2023 10:03:33 +0100 Subject: [PATCH 12/79] link to pthreads even if disabled threading in core --- cpp/CMakeLists.txt | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 7bd97a1168e9..26875a063b29 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -911,11 +911,9 @@ endif() # Handle platform-related libraries like -pthread set(ARROW_SYSTEM_LINK_LIBS) -if(!ARROW_DISABLE_THREADING) - list(APPEND ARROW_SYSTEM_LINK_LIBS Threads::Threads) - if(CMAKE_THREAD_LIBS_INIT) - string(APPEND ARROW_PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") - endif() +list(APPEND ARROW_SYSTEM_LINK_LIBS Threads::Threads) +if(CMAKE_THREAD_LIBS_INIT) + string(APPEND ARROW_PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") endif() if(WIN32) From 399d5ebd7d754e4ba9ff0951e2aaa851b2a7199a Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 26 Apr 2023 10:28:07 +0100 Subject: [PATCH 13/79] fix cast warning --- cpp/src/arrow/util/thread_pool.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index b10aa03af9f4..11ac01ba4a6f 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -93,7 +93,7 @@ SerialExecutor::~SerialExecutor() { int SerialExecutor::GetNumTasks() { auto state = state_; - return state_->task_queue.size(); + return (int)(state_->task_queue.size()); } #ifdef ARROW_DISABLE_THREADING From 6555d0236fe5b5b96af52a793e9a8048148de6ed Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 26 Apr 2023 10:36:46 +0100 Subject: [PATCH 14/79] test fixes --- cpp/src/arrow/util/thread_pool_test.cc | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index bce07d6908a1..451378d756f7 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -656,6 +656,19 @@ TEST_F(TestThreadPool, QuickShutdown) { add_tester.CheckNotAllComputed(); } +#ifdef ARROW_DISABLE_THREADING +TEST_F(TestThreadPool, SetCapacity) { + auto pool = this->MakeThreadPool(5); + + // capacity should always be 1, so all these things check for 1 + ASSERT_EQ(pool->GetCapacity(), 1); + ASSERT_EQ(pool->GetActualCapacity(), 1); + + ASSERT_OK(pool->SetCapacity(7)); + ASSERT_EQ(pool->GetCapacity(), 1); + +} +#else// ARROW_DISABLE_THREADING TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); @@ -717,7 +730,7 @@ TEST_F(TestThreadPool, SetCapacity) { // Ensure nothing got stuck ASSERT_OK(pool->Shutdown()); } - +#endif // Test Submit() functionality TEST_F(TestThreadPool, Submit) { From d941d12085caba627a892f669c71c1973e78cb7c Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 26 Apr 2023 14:05:21 +0100 Subject: [PATCH 15/79] replaced missing lock --- cpp/src/arrow/util/thread_pool.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 11ac01ba4a6f..280201524e72 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -309,6 +309,7 @@ void SerialExecutor::RunLoop() { } // Can't break here because there may be cleanup tasks down the chain we still // need to run. + lk.lock(); } } // In this case we must be waiting on work from external (e.g. I/O) executors. Wait @@ -316,7 +317,6 @@ void SerialExecutor::RunLoop() { state_->wait_for_tasks.wait(lk, [&] { return state_->paused || state_->finished || !state_->task_queue.empty(); }); - } state_->current_thread = {}; } @@ -368,6 +368,7 @@ ThreadPool::~ThreadPool() // NOP } + #else // ARROW_DISABLE_THREADING struct ThreadPool::State { @@ -718,6 +719,8 @@ int ThreadPool::DefaultCapacity() { return capacity; } + + #endif //ARROW_DISABLE_THREADING // Helper for the singleton pattern From a78d8875d04de0f02d9665420b33a33b7ccec441 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 26 Apr 2023 14:25:16 +0100 Subject: [PATCH 16/79] fixed missing method in threadpool with threads disabled --- cpp/src/arrow/util/thread_pool.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 3f4bb0333828..ef8cc95122b0 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -440,6 +440,9 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor return 1; } + int GetActualCapacity() override { return 1; }; + + bool OwnsThisThread() override { return true; From 6da6814d5474304adfd725fa90ec4df5ae892104 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 30 Apr 2023 10:50:58 +0100 Subject: [PATCH 17/79] put lock in correct place --- cpp/src/arrow/util/thread_pool.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 280201524e72..5876e8458e59 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -309,8 +309,8 @@ void SerialExecutor::RunLoop() { } // Can't break here because there may be cleanup tasks down the chain we still // need to run. - lk.lock(); } + lk.lock(); } // In this case we must be waiting on work from external (e.g. I/O) executors. Wait // for tasks to arrive (typically via transferred futures). From 8496eada9f9c2a4221f1585b9f35e35398adadc7 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 30 Apr 2023 10:51:53 +0100 Subject: [PATCH 18/79] removed override --- cpp/src/arrow/util/thread_pool.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index ef8cc95122b0..9c05461fedd2 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -440,7 +440,7 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor return 1; } - int GetActualCapacity() override { return 1; }; + int GetActualCapacity() { return 1; }; bool OwnsThisThread() override From 9acbf795734a9c4c99f72b53e16b0cf49a7ab3e7 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 13:53:05 +0100 Subject: [PATCH 19/79] made future::wait check other tasks --- cpp/src/arrow/util/future.cc | 41 +++++++++++++++++++++++++------ cpp/src/arrow/util/thread_pool.cc | 7 +++++- cpp/src/arrow/util/thread_pool.h | 6 ++++- 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index c430ad1fc738..cc46542517ef 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -149,17 +149,44 @@ class ConcreteFutureImpl : public FutureImpl { } void DoWait() { - std::unique_lock lock(mutex_); - - cv_.wait(lock, [this] { return IsFutureFinished(state_); }); + #ifdef ARROW_DISABLE_THREADING + while(true) + { + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + if(IsFutureFinished(state_)) + { + return; + } + } + #else + std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { return IsFutureFinished(state_); }); + #endif } bool DoWait(double seconds) { - std::unique_lock lock(mutex_); + #ifdef ARROW_DISABLE_THREADING + auto start = std::chrono::steady_clock::now(); + std::chrono::duration fsec=std::chrono::duration(seconds); + while(std::chrono::steady_clock::now()-start < fsec) + { + // run one task then check time + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + if(IsFutureFinished(state_)) + { + return true; + } + } + return IsFutureFinished(state_); + + #else + + std::unique_lock lock(mutex_); - cv_.wait_for(lock, std::chrono::duration(seconds), - [this] { return IsFutureFinished(state_); }); - return IsFutureFinished(state_); + cv_.wait_for(lock, std::chrono::duration(seconds), + [this] { return IsFutureFinished(state_); }); + return IsFutureFinished(state_); + #endif } std::mutex mutex_; diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 5876e8458e59..79d7551941b3 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -194,7 +194,7 @@ bool SerialExecutor::OwnsThisThread() { } #ifdef ARROW_DISABLE_THREADING -void SerialExecutor::RunTasksOnAllExecutors() +void SerialExecutor::RunTasksOnAllExecutors(bool once_only) { bool run_task=true; while(run_task) @@ -215,6 +215,11 @@ void SerialExecutor::RunTasksOnAllExecutors() std::move(task.stop_callback)(task.stop_token.Poll()); } } + if(once_only) + { + run_task=false; + break; + } } } } diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 9c05461fedd2..e745113872e0 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -373,6 +373,11 @@ class ARROW_EXPORT SerialExecutor : public Executor { return Iterator(SerialIterator{std::move(serial_executor), std::move(generator)}); } +#ifdef ARROW_DISABLE_THREADING + static void RunTasksOnAllExecutors(bool once_only=false); // run loop until everything works okay +#endif + + protected: virtual void RunLoop(); @@ -406,7 +411,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; - static void RunTasksOnAllExecutors(); // run loop until everything works okay #endif // ARROW_DISABLE_THREADING From 38212078859b567727ead2169c9b0b27f886de06 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 14:07:49 +0100 Subject: [PATCH 20/79] made task group run execution tasks while waiting to finish --- cpp/src/arrow/util/task_group.cc | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 932f642041d4..9ebd3994672f 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -128,14 +128,22 @@ class ThreadedTaskGroup : public TaskGroup { bool ok() const override { return ok_.load(); } Status Finish() override { - std::unique_lock lock(mutex_); - if (!finished_) { - cv_.wait(lock, [&]() { return nremaining_.load() == 0; }); - // Current tasks may start other tasks, so only set this when done + #ifdef ARROW_DISABLE_THREADING + while(!finished_ && nremaining_.load() != 0 ) + { + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } finished_ = true; + #else + std::unique_lock lock(mutex_); + if (!finished_) { + cv_.wait(lock, [&]() { return nremaining_.load() == 0; }); + // Current tasks may start other tasks, so only set this when done + finished_ = true; + } + #endif + return status_; } - return status_; - } Future<> FinishAsync() override { std::lock_guard lock(mutex_); From 5946cc7296d4483543e046d5e07d96e4194cd51e Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 14:26:41 +0100 Subject: [PATCH 21/79] track current executor without threads --- cpp/src/arrow/util/future.cc | 4 ++++ cpp/src/arrow/util/future_test.cc | 9 ++++++++- cpp/src/arrow/util/thread_pool.cc | 13 +++++++++++++ cpp/src/arrow/util/thread_pool.h | 4 ++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index cc46542517ef..4a3f85fa7365 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -89,7 +89,11 @@ class ConcreteFutureImpl : public FutureImpl { case ShouldSchedule::IfUnfinished: return !in_add_callback; case ShouldSchedule::IfDifferentExecutor: +#ifdef ARROW_DISABLE_THREADING + return !(callback_record.options.executor==SerialExecutor::GetCurrentExecutor()); +#else return !callback_record.options.executor->OwnsThisThread(); +#endif default: DCHECK(false) << "Unrecognized ShouldSchedule option"; return false; diff --git a/cpp/src/arrow/util/future_test.cc b/cpp/src/arrow/util/future_test.cc index 689b7c3df62d..6b941c25f86e 100644 --- a/cpp/src/arrow/util/future_test.cc +++ b/cpp/src/arrow/util/future_test.cc @@ -1100,8 +1100,11 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { auto fut0_done = fut0.Then( [&] { // marked finished on main thread -> must be scheduled to executor +#ifdef ARROW_DISABLE_THREADING + fut0_on_executor.store(executor==SerialExecutor::GetCurrentExecutor()); +#else fut0_on_executor.store(executor.OwnsThisThread()); - +#endif fut1.MarkFinished(); }, pass_err, options); @@ -1109,7 +1112,11 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { auto fut1_done = fut1.Then( [&] { // marked finished on executor -> no need to schedule +#ifdef ARROW_DISABLE_THREADING + fut1_on_executor.store(executor==SerialExecutor::GetCurrentExecutor()); +#else fut1_on_executor.store(executor.OwnsThisThread()); +#endif }, pass_err, options); diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 79d7551941b3..9df56bae282a 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -65,6 +65,7 @@ struct SerialExecutor::State { #ifdef ARROW_DISABLE_THREADING // list of all SerialExecutor objects - as we need to run tasks from all pools at once in Run() std::unordered_set SerialExecutor::all_executors; +SerialExecutor* SerialExecutor::current_executor=NULL; #endif SerialExecutor::SerialExecutor() : state_(std::make_shared()) @@ -205,6 +206,8 @@ void SerialExecutor::RunTasksOnAllExecutors(bool once_only) SerialExecutor* exe = *it; if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) { + SerialExecutor* old_exe=current_executor; + current_executor=exe; Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); run_task=true; @@ -215,6 +218,8 @@ void SerialExecutor::RunTasksOnAllExecutors(bool once_only) std::move(task.stop_callback)(task.stop_token.Poll()); } } + current_executor=old_exe; + if(once_only) { run_task=false; @@ -237,9 +242,12 @@ void SerialExecutor::RunLoop() // async task to finish from another thread pool). We still need to check paused // because sometimes we will pause even with work leftover when processing // an async generator + while (!state_->paused && !state_->task_queue.empty()) { Task task = std::move(state_->task_queue.front()); state_->task_queue.pop_front(); + SerialExecutor* old_exe=current_executor; + current_executor=this; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); } else { @@ -249,6 +257,7 @@ void SerialExecutor::RunLoop() // Can't break here because there may be cleanup tasks down the chain we still // need to run. } + current_executor=old_exe; } // In this case we must be waiting on work from external (e.g. I/O) executors. Run things // in all serialexecutors until we have something in queue @@ -269,6 +278,8 @@ void SerialExecutor::RunLoop() SerialExecutor* exe = *it; if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) { + SerialExecutor* old_exe=current_executor; + current_executor=exe; Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); if (!task.stop_token.IsStopRequested()) { @@ -278,7 +289,9 @@ void SerialExecutor::RunLoop() std::move(task.stop_callback)(task.stop_token.Poll()); } } + current_executor=old_exe; } + break; } count-=1; diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index e745113872e0..19b614a119de 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -375,6 +375,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { #ifdef ARROW_DISABLE_THREADING static void RunTasksOnAllExecutors(bool once_only=false); // run loop until everything works okay + static SerialExecutor* GetCurrentExecutor(); #endif @@ -411,6 +412,9 @@ class ARROW_EXPORT SerialExecutor : public Executor { // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; + // without threading we can't tell which executor called the + // current process - so we set it in spawning the task + static SerialExecutor* current_executor; #endif // ARROW_DISABLE_THREADING From 3c5a78c8f6b378bde1586929bc9e9064caaea87f Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 14:28:01 +0100 Subject: [PATCH 22/79] forgot namespace - fixed --- cpp/src/arrow/util/future.cc | 2 +- cpp/src/arrow/util/future_test.cc | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 4a3f85fa7365..ebbcb90b5d8f 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -90,7 +90,7 @@ class ConcreteFutureImpl : public FutureImpl { return !in_add_callback; case ShouldSchedule::IfDifferentExecutor: #ifdef ARROW_DISABLE_THREADING - return !(callback_record.options.executor==SerialExecutor::GetCurrentExecutor()); + return !(callback_record.options.executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); #else return !callback_record.options.executor->OwnsThisThread(); #endif diff --git a/cpp/src/arrow/util/future_test.cc b/cpp/src/arrow/util/future_test.cc index 6b941c25f86e..9676ff7ca0bd 100644 --- a/cpp/src/arrow/util/future_test.cc +++ b/cpp/src/arrow/util/future_test.cc @@ -1101,7 +1101,7 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { [&] { // marked finished on main thread -> must be scheduled to executor #ifdef ARROW_DISABLE_THREADING - fut0_on_executor.store(executor==SerialExecutor::GetCurrentExecutor()); + fut0_on_executor.store(executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); #else fut0_on_executor.store(executor.OwnsThisThread()); #endif @@ -1113,7 +1113,7 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { [&] { // marked finished on executor -> no need to schedule #ifdef ARROW_DISABLE_THREADING - fut1_on_executor.store(executor==SerialExecutor::GetCurrentExecutor()); + fut1_on_executor.store(executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); #else fut1_on_executor.store(executor.OwnsThisThread()); #endif From 538014154f23f57eef6b755c883c31b789af34ec Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 15:10:08 +0100 Subject: [PATCH 23/79] fixes to futures for more reliable behaviour --- cpp/src/arrow/io/memory_test.cc | 2 + cpp/src/arrow/util/future.cc | 6 +-- cpp/src/arrow/util/future_test.cc | 12 +----- cpp/src/arrow/util/thread_pool.cc | 65 +++++++++++++++++++++---------- cpp/src/arrow/util/thread_pool.h | 17 ++++++-- 5 files changed, 63 insertions(+), 39 deletions(-) diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index cdcbe240f858..d447d9967bdc 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -869,6 +869,7 @@ TEST(CacheOptions, Basics) { check(CacheOptions::MakeFromNetworkMetrics(5, 500, .75, 5), 2.5, 5); } +#ifndef ARROW_DISABLE_THREADING TEST(IOThreadPool, Capacity) { // Simple sanity check auto pool = internal::GetIOThreadPool(); @@ -878,6 +879,7 @@ TEST(IOThreadPool, Capacity) { ASSERT_OK(SetIOThreadPoolCapacity(capacity + 1)); ASSERT_EQ(GetIOThreadPoolCapacity(), capacity + 1); } +#endif } // namespace io } // namespace arrow diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index ebbcb90b5d8f..a9fd0d1016cf 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -89,11 +89,7 @@ class ConcreteFutureImpl : public FutureImpl { case ShouldSchedule::IfUnfinished: return !in_add_callback; case ShouldSchedule::IfDifferentExecutor: -#ifdef ARROW_DISABLE_THREADING - return !(callback_record.options.executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); -#else - return !callback_record.options.executor->OwnsThisThread(); -#endif + return !callback_record.options.executor->IsCurrentExecutor(); default: DCHECK(false) << "Unrecognized ShouldSchedule option"; return false; diff --git a/cpp/src/arrow/util/future_test.cc b/cpp/src/arrow/util/future_test.cc index 9676ff7ca0bd..b9ae1beea041 100644 --- a/cpp/src/arrow/util/future_test.cc +++ b/cpp/src/arrow/util/future_test.cc @@ -1100,11 +1100,7 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { auto fut0_done = fut0.Then( [&] { // marked finished on main thread -> must be scheduled to executor -#ifdef ARROW_DISABLE_THREADING - fut0_on_executor.store(executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); -#else - fut0_on_executor.store(executor.OwnsThisThread()); -#endif + fut0_on_executor.store(executor.IsCurrentExecutor()); fut1.MarkFinished(); }, pass_err, options); @@ -1112,11 +1108,7 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { auto fut1_done = fut1.Then( [&] { // marked finished on executor -> no need to schedule -#ifdef ARROW_DISABLE_THREADING - fut1_on_executor.store(executor==arrow::internal::SerialExecutor::GetCurrentExecutor()); -#else - fut1_on_executor.store(executor.OwnsThisThread()); -#endif + fut1_on_executor.store(executor.IsCurrentExecutor()); }, pass_err, options); diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 9df56bae282a..88b9becc5f7f 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -66,6 +66,12 @@ struct SerialExecutor::State { // list of all SerialExecutor objects - as we need to run tasks from all pools at once in Run() std::unordered_set SerialExecutor::all_executors; SerialExecutor* SerialExecutor::current_executor=NULL; +SerialExecutor* SerialExecutor::GetCurrentExecutor() +{ + return current_executor; +} +SerialExecutor* SerialExecutor::last_called_executor=NULL; + #endif SerialExecutor::SerialExecutor() : state_(std::make_shared()) @@ -196,36 +202,53 @@ bool SerialExecutor::OwnsThisThread() { #ifdef ARROW_DISABLE_THREADING void SerialExecutor::RunTasksOnAllExecutors(bool once_only) -{ +{ + if(last_called_executor!=NULL && all_executors.count(last_called_executor)==0) + { + last_called_executor=NULL; + } bool run_task=true; while(run_task) { run_task=false; - for(auto it=all_executors.begin();it!=all_executors.end();it++) + for(auto it=all_executors.begin();it!=all_executors.end();++it) { - SerialExecutor* exe = *it; - if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) + if(last_called_executor!=NULL) + { + if(all_executors.count(last_called_executor)==0 || last_called_executor==*it) { - SerialExecutor* old_exe=current_executor; - current_executor=exe; - Task task = std::move(exe->state_->task_queue.front()); - exe->state_->task_queue.pop_front(); - run_task=true; - if (!task.stop_token.IsStopRequested()) { - std::move(task.callable)(); - } else { - if (task.stop_callback) { - std::move(task.stop_callback)(task.stop_token.Poll()); - } + // found the last one (or it doesn't exist ih the set any more) + // now we can start running things + last_called_executor=NULL; + } + // skip until after we have seen the last executor we called + // so that we do things nicely in turn + continue; + } + SerialExecutor* exe = *it; + if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) + { + SerialExecutor* old_exe=current_executor; + current_executor=exe; + Task task = std::move(exe->state_->task_queue.front()); + exe->state_->task_queue.pop_front(); + run_task=true; + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); } - current_executor=old_exe; + } + current_executor=old_exe; - if(once_only) - { - run_task=false; - break; - } + if(once_only) + { + last_called_executor=exe; + run_task=false; + break; } + } } } } diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 19b614a119de..c7878886fc46 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -196,6 +196,12 @@ class ARROW_EXPORT Executor { // Executor. Returns false if this Executor does not support this property. virtual bool OwnsThisThread() { return false; } + // Return true if this is the current executor being called + // n.b. this defaults to just calling OwnsThisThread + // unless the threadpool is disabled + virtual bool IsCurrentExecutor() {return OwnsThisThread();} + + /// \brief An interface to represent something with a custom destructor /// /// \see KeepAlive @@ -376,6 +382,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { #ifdef ARROW_DISABLE_THREADING static void RunTasksOnAllExecutors(bool once_only=false); // run loop until everything works okay static SerialExecutor* GetCurrentExecutor(); + + virtual bool IsCurrentExecutor() {return current_executor==this;} + + #endif @@ -412,6 +422,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; + // a pointer to the last one called by the loop + // so all tasks get spawned equally + // on multiple calls to RunTasksOnAllExecutors + static SerialExecutor* last_called_executor; // without threading we can't tell which executor called the // current process - so we set it in spawning the task static SerialExecutor* current_executor; @@ -450,7 +464,6 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor int GetActualCapacity() { return 1; }; - bool OwnsThisThread() override { return true; @@ -504,8 +517,6 @@ class ARROW_EXPORT ThreadPool : public Executor { // match this value. int GetCapacity() override; - bool OwnsThisThread() override; - // Return the number of tasks either running or in the queue. int GetNumTasks(); From f0f0565e639ecc6bc5b04d7b72b6bcc521421576 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 15:16:33 +0100 Subject: [PATCH 24/79] future test fixes --- cpp/src/arrow/util/future.cc | 2 +- cpp/src/arrow/util/future_test.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index a9fd0d1016cf..34b1eae047ea 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -89,7 +89,7 @@ class ConcreteFutureImpl : public FutureImpl { case ShouldSchedule::IfUnfinished: return !in_add_callback; case ShouldSchedule::IfDifferentExecutor: - return !callback_record.options.executor->IsCurrentExecutor(); + return !(callback_record.options.executor->IsCurrentExecutor()); default: DCHECK(false) << "Unrecognized ShouldSchedule option"; return false; diff --git a/cpp/src/arrow/util/future_test.cc b/cpp/src/arrow/util/future_test.cc index b9ae1beea041..87891e48efa5 100644 --- a/cpp/src/arrow/util/future_test.cc +++ b/cpp/src/arrow/util/future_test.cc @@ -1073,7 +1073,7 @@ TEST_F(FutureSchedulingTest, ScheduleIfDifferentExecutor) { struct : internal::Executor { int GetCapacity() override { return pool_->GetCapacity(); } - bool OwnsThisThread() override { return pool_->OwnsThisThread(); } + bool IsCurrentExecutor() override { return pool_->IsCurrentExecutor(); } Status SpawnReal(internal::TaskHints hints, internal::FnOnce task, StopToken stop_token, StopCallback&& stop_callback) override { From 313489b6f4146424433726202ed26a4ea7132829 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 1 May 2023 15:21:05 +0100 Subject: [PATCH 25/79] fix error in threadpool.h --- cpp/src/arrow/util/thread_pool.h | 1 + 1 file changed, 1 insertion(+) diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index c7878886fc46..a3aed538a202 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -520,6 +520,7 @@ class ARROW_EXPORT ThreadPool : public Executor { // Return the number of tasks either running or in the queue. int GetNumTasks(); + bool OwnsThisThread() override; // Dynamically change the number of worker threads. // // This function always returns immediately. From ce25af73dc26bf54389f501a9d341b422ef47ee3 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 2 May 2023 13:04:55 +0100 Subject: [PATCH 26/79] made tasks only launch when waited for --- cpp/src/arrow/util/task_group.cc | 4 ++++ cpp/src/arrow/util/thread_pool.cc | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 9ebd3994672f..2455c3a03de4 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -218,7 +218,11 @@ std::shared_ptr TaskGroup::MakeSerial(StopToken stop_token) { std::shared_ptr TaskGroup::MakeThreaded(Executor* thread_pool, StopToken stop_token) { +#ifdef ARROW_DISABLE_THREADING + return MakeSerial(stop_token); +#else return std::shared_ptr(new ThreadedTaskGroup{thread_pool, stop_token}); +#endif } } // namespace internal diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 88b9becc5f7f..8300e064eba2 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -124,7 +124,7 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, } state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); - SerialExecutor::RunTasksOnAllExecutors(); + return Status::OK(); } From 9e3598d8f99aa6244a4f2e2f62bb61c474cfdb6e Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 2 May 2023 14:29:25 +0100 Subject: [PATCH 27/79] made runloop quit correctly on pause --- cpp/src/arrow/util/thread_pool.cc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 8300e064eba2..c65be805a49f 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -282,16 +282,18 @@ void SerialExecutor::RunLoop() } current_executor=old_exe; } + + // if we are not paused, empty of tasks but not finished: // In this case we must be waiting on work from external (e.g. I/O) executors. Run things // in all serialexecutors until we have something in queue int executor_pos=0; - while ((state_->paused || state_->task_queue.empty() ) && !state_->finished) + while (!state_->paused && (state_->task_queue.empty() && !state_->finished) ) { // we cycle round executors in turn, in case e.g. we are reading multiple // file inputs or something like that // n.b. we don't do this with an iterator because - // these calls may delete or add executors + // these calls may themselves delete or add executors int count=(executor_pos)%all_executors.size(); for(auto it=all_executors.begin();it!=all_executors.end();it++) { From a500fbcf3dac87fc3af477c7a8a94df8b2124ba8 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 3 May 2023 13:40:57 +0100 Subject: [PATCH 28/79] test fixes --- cpp/src/arrow/acero/bloom_filter.cc | 3 + cpp/src/arrow/acero/bloom_filter_test.cc | 8 +- cpp/src/arrow/acero/plan_test.cc | 9 ++- cpp/src/arrow/acero/task_util.cc | 5 +- cpp/src/arrow/acero/task_util_test.cc | 11 +++ cpp/src/arrow/testing/gtest_util.cc | 18 +++++ cpp/src/arrow/util/future.cc | 4 +- cpp/src/arrow/util/thread_pool.cc | 94 ++++++++++-------------- cpp/src/arrow/util/thread_pool.h | 9 ++- 9 files changed, 98 insertions(+), 63 deletions(-) diff --git a/cpp/src/arrow/acero/bloom_filter.cc b/cpp/src/arrow/acero/bloom_filter.cc index ad5e66ded061..79a9dd870194 100644 --- a/cpp/src/arrow/acero/bloom_filter.cc +++ b/cpp/src/arrow/acero/bloom_filter.cc @@ -426,6 +426,9 @@ void BloomFilterBuilder_Parallel::CleanUp() { std::unique_ptr BloomFilterBuilder::Make( BloomFilterBuildStrategy strategy) { +#ifdef ARROW_DISABLE_THREADING + strategy=BloomFilterBuildStrategy::SINGLE_THREADED; +#endif switch (strategy) { case BloomFilterBuildStrategy::SINGLE_THREADED: { std::unique_ptr impl{new BloomFilterBuilder_SingleThreaded()}; diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index de433ac68c11..4be492126687 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -472,8 +472,10 @@ TEST(BloomFilter, Basic) { std::vector strategy; strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); -#ifndef ARROW_VALGRIND +#ifndef ARROW_DISABLE_THREADING +#ifndef ARROW_VALGRIND strategy.push_back(BloomFilterBuildStrategy::PARALLEL); +#endif #endif static constexpr int64_t min_rows_for_large = 2 * 1024 * 1024; @@ -507,7 +509,11 @@ TEST(BloomFilter, Scaling) { num_build.push_back(4000000); std::vector strategy; +#ifdef ARROW_DISABLE_THREADING + strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); +#else strategy.push_back(BloomFilterBuildStrategy::PARALLEL); +#endif for (bool use_avx2 : {false, true}) { for (size_t istrategy = 0; istrategy < strategy.size(); ++istrategy) { diff --git a/cpp/src/arrow/acero/plan_test.cc b/cpp/src/arrow/acero/plan_test.cc index 8ec5c0f70a95..6594073e5886 100644 --- a/cpp/src/arrow/acero/plan_test.cc +++ b/cpp/src/arrow/acero/plan_test.cc @@ -985,9 +985,9 @@ TEST(ExecPlanExecution, StressSourceSinkStopped) { EXPECT_THAT(first_batch_fut, Finishes(ResultWith(Optional(random_data.batches[0])))); } - - plan->StopProducing(); - Future<> finished = plan->finished(); + + plan->StopProducing(); + Future<> finished = plan->finished(); CheckFinishesCancelledOrOk(plan->finished()); } } @@ -1602,6 +1602,9 @@ TEST(ExecPlan, SourceEnforcesBatchLimit) { } TEST(ExecPlanExecution, SegmentedAggregationWithMultiThreading) { +#ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading enabled"; +#endif BatchesWithSchema data; data.batches = {ExecBatchFromJSON({int32()}, "[[1]]")}; data.schema = schema({field("i32", int32())}); diff --git a/cpp/src/arrow/acero/task_util.cc b/cpp/src/arrow/acero/task_util.cc index 8127902e69e9..a70578f61ac8 100644 --- a/cpp/src/arrow/acero/task_util.cc +++ b/cpp/src/arrow/acero/task_util.cc @@ -328,10 +328,13 @@ Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) } ARROW_DCHECK(register_finished_); - +#ifdef ARROW_DISABLE_THREADING + return ExecuteMore(thread_id, 1, true); +#else if (use_sync_execution_) { return ExecuteMore(thread_id, 1, true); } +#endif int num_new_tasks = num_tasks_finished; for (;;) { diff --git a/cpp/src/arrow/acero/task_util_test.cc b/cpp/src/arrow/acero/task_util_test.cc index dafb6b24b4cd..d2fc2fc01752 100644 --- a/cpp/src/arrow/acero/task_util_test.cc +++ b/cpp/src/arrow/acero/task_util_test.cc @@ -95,12 +95,16 @@ TaskScheduler::TaskGroupContinuationImpl MakeFinalContinuation( }; } + // This test simulates one of the current use patterns of the // task scheduler. There are a number of groups. The groups // are allocated to stages. All groups in a stage execute // concurrently. When all groups in that stage finish the next // stage is started. TEST(TaskScheduler, Stress) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif constexpr int kNumThreads = 8; constexpr int kNumGroups = 8; constexpr int kGroupsPerStage = 3; @@ -176,11 +180,18 @@ TEST(TaskScheduler, Stress) { // thread starts a task group while another thread is finishing // the last of its tasks. TEST(TaskScheduler, StressTwo) { + + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif + + constexpr int kNumThreads = 16; constexpr int kNumGroups = 8; constexpr int kTasksPerGroup = 1; constexpr int kIterations = 1000; + ThreadIndexer thread_indexer; int num_threads = std::min(static_cast(thread_indexer.Capacity()), kNumThreads); ASSERT_OK_AND_ASSIGN(std::shared_ptr thread_pool, diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 37c430892d02..c3c176ca03f8 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -706,8 +706,26 @@ void TestInitialized(const ArrayData& array) { } void SleepFor(double seconds) { +#ifdef ARROW_DISABLE_THREADING + std::chrono::duration secs_left=std::chrono::duration(seconds); + auto start_time = std::chrono::steady_clock::now(); + auto end_time= start_time+secs_left; + auto now=start_time; + while(now < end_time) + { + bool run_task=arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + now= std::chrono::steady_clock::now(); + if(!run_task) + { + // all executors are empty, just sleep for the rest of the time + std::this_thread::sleep_for(end_time-now); + } + // run one task then check time + } +#else std::this_thread::sleep_for( std::chrono::nanoseconds(static_cast(seconds * 1e9))); +#endif } #ifdef _WIN32 diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 34b1eae047ea..a1a90f4f7460 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -152,11 +152,11 @@ class ConcreteFutureImpl : public FutureImpl { #ifdef ARROW_DISABLE_THREADING while(true) { - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); if(IsFutureFinished(state_)) { return; } + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); } #else std::unique_lock lock(mutex_); @@ -171,11 +171,11 @@ class ConcreteFutureImpl : public FutureImpl { while(std::chrono::steady_clock::now()-start < fsec) { // run one task then check time - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); if(IsFutureFinished(state_)) { return true; } + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); } return IsFutureFinished(state_); diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index c65be805a49f..590d1b637197 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -124,7 +124,7 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, } state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); - + return Status::OK(); } @@ -201,20 +201,25 @@ bool SerialExecutor::OwnsThisThread() { } #ifdef ARROW_DISABLE_THREADING -void SerialExecutor::RunTasksOnAllExecutors(bool once_only) +bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { if(last_called_executor!=NULL && all_executors.count(last_called_executor)==0) { last_called_executor=NULL; } bool run_task=true; - while(run_task) + bool keep_going=true; + while(keep_going) { run_task=false; + keep_going=false; for(auto it=all_executors.begin();it!=all_executors.end();++it) { if(last_called_executor!=NULL) { + // always rerun loop if we have a last_called_executor, otherwise + // we drop out before everything is + keep_going=true; if(all_executors.count(last_called_executor)==0 || last_called_executor==*it) { // found the last one (or it doesn't exist ih the set any more) @@ -226,7 +231,12 @@ void SerialExecutor::RunTasksOnAllExecutors(bool once_only) continue; } SerialExecutor* exe = *it; - if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) + // don't make reentrant calls inside a serialexecutor + if(exe==current_executor && !exe->IsReentrant()) + { + continue; + } + if(exe->state_->paused==false && exe->state_->task_queue.empty()==false) { SerialExecutor* old_exe=current_executor; current_executor=exe; @@ -245,12 +255,16 @@ void SerialExecutor::RunTasksOnAllExecutors(bool once_only) if(once_only) { last_called_executor=exe; - run_task=false; + keep_going=false; break; + }else + { + keep_going=true; } } } } + return run_task; } // run tasks in this thread and queue things from other executors if required @@ -260,70 +274,42 @@ void SerialExecutor::RunLoop() // If paused we break out immediately. If finished we only break out // when all work is done. while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { - - // The inner loop is to check if we need to sleep (e.g. while waiting on some - // async task to finish from another thread pool). We still need to check paused - // because sometimes we will pause even with work leftover when processing - // an async generator - + // first empty us until paused or empty while (!state_->paused && !state_->task_queue.empty()) { Task task = std::move(state_->task_queue.front()); state_->task_queue.pop_front(); - SerialExecutor* old_exe=current_executor; + auto last_executor=current_executor; current_executor=this; if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); } else { if (task.stop_callback) { std::move(task.stop_callback)(task.stop_token.Poll()); } - // Can't break here because there may be cleanup tasks down the chain we still - // need to run. } - current_executor=old_exe; + current_executor=last_executor; } - - // if we are not paused, empty of tasks but not finished: - // In this case we must be waiting on work from external (e.g. I/O) executors. Run things - // in all serialexecutors until we have something in queue - - int executor_pos=0; - while (!state_->paused && (state_->task_queue.empty() && !state_->finished) ) + if(state_->paused || state_->finished) { - // we cycle round executors in turn, in case e.g. we are reading multiple - // file inputs or something like that - // n.b. we don't do this with an iterator because - // these calls may themselves delete or add executors - int count=(executor_pos)%all_executors.size(); - for(auto it=all_executors.begin();it!=all_executors.end();it++) - { - if (count==0) - { - // run a single task from this executor if it isn't paused - SerialExecutor* exe = *it; - if(!(exe->state_->paused || exe->state_->task_queue.empty() || exe->state_->finished)) - { - SerialExecutor* old_exe=current_executor; - current_executor=exe; - Task task = std::move(exe->state_->task_queue.front()); - exe->state_->task_queue.pop_front(); - if (!task.stop_token.IsStopRequested()) { - std::move(task.callable)(); - } else { - if (task.stop_callback) { - std::move(task.stop_callback)(task.stop_token.Poll()); - } - } - current_executor=old_exe; - } - - break; - } - count-=1; - } - executor_pos+=1; + break; + } + // now wait for anything on other executors (unless we're finished in which case it will drop out of + // the outer loop + if(!IsReentrant()) + { + // stop runtasks from running our tasks by pausing us during the call + // otherwise things could happen out of order + bool old_paused=state_->paused; + state_->paused=true; + RunTasksOnAllExecutors(true); + state_->paused=old_paused; + }else + { + RunTasksOnAllExecutors(true); } } + } #else //ARROW_DISABLE_THREADING diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index a3aed538a202..66b97bf75f7e 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -380,7 +380,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { } #ifdef ARROW_DISABLE_THREADING - static void RunTasksOnAllExecutors(bool once_only=false); // run loop until everything works okay + // run loop until everything is done (or one go round loop if once_only=True) + // returns true if any tasks were run in the last go round the loop (i.e. if it + // returns false, all executors are waiting) + static bool RunTasksOnAllExecutors(bool once_only=false); static SerialExecutor* GetCurrentExecutor(); virtual bool IsCurrentExecutor() {return current_executor==this;} @@ -416,9 +419,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { final_fut.AddCallback([this](const FTSync&) { Finish(); }); RunLoop(); return final_fut; - } + } #ifdef ARROW_DISABLE_THREADING + virtual bool IsReentrant(){return false;}; // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; @@ -489,6 +493,7 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor protected: static std::shared_ptr MakeCpuThreadPool(); ThreadPool(); + virtual bool IsReentrant(){return true;} }; From 5b2f75289c95c72bcaf113ca9e51b3de7570248b Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 5 May 2023 11:21:49 +0100 Subject: [PATCH 29/79] test fixes --- cpp/src/arrow/acero/CMakeLists.txt | 12 +- cpp/src/arrow/acero/asof_join_node.cc | 3 + cpp/src/arrow/acero/asof_join_node_test.cc | 2 +- cpp/src/arrow/engine/substrait/serde_test.cc | 3 + cpp/src/arrow/util/iterator_test.cc | 2 + cpp/src/arrow/util/task_group.cc | 4 - cpp/src/arrow/util/thread_pool.cc | 119 +++++++++++++------ cpp/src/arrow/util/thread_pool.h | 27 +++-- cpp/src/arrow/util/thread_pool_test.cc | 40 ++++++- 9 files changed, 151 insertions(+), 61 deletions(-) diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index 258dcb5580c3..2090629f2fe6 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -55,6 +55,7 @@ set(ARROW_ACERO_SRCS union_node.cc util.cc) + append_acero_avx2_src(bloom_filter_avx2.cc) append_acero_avx2_src(swiss_join_avx2.cc) @@ -163,7 +164,14 @@ add_arrow_acero_test(hash_join_node_test SOURCES hash_join_node_test.cc bloom_filter_test.cc) add_arrow_acero_test(pivot_longer_node_test SOURCES pivot_longer_node_test.cc test_nodes.cc) -add_arrow_acero_test(asof_join_node_test SOURCES asof_join_node_test.cc test_nodes.cc) + +# asof_join_node uses std::thread internally +# and doesn't use ThreadPool so it will +# be broken if threading is turned off +if(ARROW_DISABLE_THREADING!=ON) + add_arrow_acero_test(asof_join_node_test SOURCES asof_join_node_test.cc test_nodes.cc) +endif() + add_arrow_acero_test(tpch_node_test SOURCES tpch_node_test.cc) add_arrow_acero_test(union_node_test SOURCES union_node_test.cc) add_arrow_acero_test(groupby_test SOURCES groupby_test.cc) @@ -213,7 +221,9 @@ if(ARROW_BUILD_BENCHMARKS) add_arrow_acero_benchmark(project_benchmark SOURCES benchmark_util.cc project_benchmark.cc) +if(ARROW_DISABLE_THREADING!=ON) add_arrow_acero_benchmark(asof_join_benchmark SOURCES asof_join_benchmark.cc) +endif() add_arrow_acero_benchmark(tpch_benchmark SOURCES tpch_benchmark.cc) diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index e48d6c3bf9b5..232e3803ef19 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -1520,6 +1520,9 @@ class AsofJoinNode : public ExecNode { // Plan has already aborted. Do not start process thread return Status::OK(); } + #ifdef ARROW_DISABLE_THREADING + return Status::ExecutionError("ASOF join requires threading enabled"); + #endif process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); return Status::OK(); } diff --git a/cpp/src/arrow/acero/asof_join_node_test.cc b/cpp/src/arrow/acero/asof_join_node_test.cc index 730a82fb097d..a3a2bc314610 100644 --- a/cpp/src/arrow/acero/asof_join_node_test.cc +++ b/cpp/src/arrow/acero/asof_join_node_test.cc @@ -1380,7 +1380,7 @@ T GetEnvValue(const std::string& var, T default_value) { } // namespace TEST(AsofJoinTest, BackpressureWithBatchesGen) { - int num_batches = GetEnvValue("ARROW_BACKPRESSURE_DEMO_NUM_BATCHES", 10); + int num_batches = GetEnvValue("ARROW_BACKPRESSURE_DEMO_NUM_BATCHES", 2); int batch_size = GetEnvValue("ARROW_BACKPRESSURE_DEMO_BATCH_SIZE", 1); return TestBackpressure(MakeIntegerBatchGenForTest, num_batches, batch_size, /*fast_delay=*/0.001, /*slow_delay=*/0.01); diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc b/cpp/src/arrow/engine/substrait/serde_test.cc index d89924b807f0..8ad1b2632e01 100644 --- a/cpp/src/arrow/engine/substrait/serde_test.cc +++ b/cpp/src/arrow/engine/substrait/serde_test.cc @@ -4458,6 +4458,9 @@ TEST(Substrait, SetRelationBasic) { } TEST(Substrait, PlanWithAsOfJoinExtension) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; + #endif // This demos an extension relation std::string substrait_json = R"({ "extensionUris": [], diff --git a/cpp/src/arrow/util/iterator_test.cc b/cpp/src/arrow/util/iterator_test.cc index ab62fcb7034b..4d3d66c7f92b 100644 --- a/cpp/src/arrow/util/iterator_test.cc +++ b/cpp/src/arrow/util/iterator_test.cc @@ -438,10 +438,12 @@ TEST(ReadaheadIterator, Trace) { ASSERT_EQ(values[i], TestInt()); } +#ifndef ARROW_DISABLE_THREADING // Values were all emitted from the same thread, and it's not this thread const auto& thread_ids = tracing->thread_ids(); ASSERT_EQ(thread_ids.size(), 1); ASSERT_NE(*thread_ids.begin(), std::this_thread::get_id()); +#endif } TEST(ReadaheadIterator, NextError) { diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 2455c3a03de4..9ebd3994672f 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -218,11 +218,7 @@ std::shared_ptr TaskGroup::MakeSerial(StopToken stop_token) { std::shared_ptr TaskGroup::MakeThreaded(Executor* thread_pool, StopToken stop_token) { -#ifdef ARROW_DISABLE_THREADING - return MakeSerial(stop_token); -#else return std::shared_ptr(new ThreadedTaskGroup{thread_pool, stop_token}); -#endif } } // namespace internal diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 590d1b637197..955b5d135c0e 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -45,6 +45,7 @@ void Executor::KeepAlive(std::shared_ptr resource) {} namespace { + struct Task { FnOnce callable; StopToken stop_token; @@ -60,6 +61,10 @@ struct SerialExecutor::State { std::thread::id current_thread; bool paused{false}; bool finished{false}; +#ifdef ARROW_DISABLE_THREADING + int max_tasks_running{1}; + int tasks_running{0}; +#endif }; #ifdef ARROW_DISABLE_THREADING @@ -78,6 +83,7 @@ SerialExecutor::SerialExecutor() : state_(std::make_shared()) { #ifdef ARROW_DISABLE_THREADING all_executors.insert(this); + state_->max_tasks_running=1; #endif } @@ -124,10 +130,20 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, } state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); - + return Status::OK(); } +void SerialExecutor::Finish() { + auto state = state_; + { + state->finished = true; + } + // empty any tasks from the loop on finish + RunLoop(); +} + + #else //ARROW_DISABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { @@ -162,26 +178,28 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, state->wait_for_tasks.notify_one(); return Status::OK(); } -#endif -void SerialExecutor::Pause() { - // Same comment as SpawnReal above + +void SerialExecutor::Finish() { auto state = state_; { std::lock_guard lk(state->mutex); - state->paused = true; + state->finished = true; } state->wait_for_tasks.notify_one(); } -void SerialExecutor::Finish() { +#endif +void SerialExecutor::Pause() { + // Same comment as SpawnReal above auto state = state_; { std::lock_guard lk(state->mutex); - state->finished = true; + state->paused = true; } state->wait_for_tasks.notify_one(); } + bool SerialExecutor::IsFinished() { std::lock_guard lk(state_->mutex); return state_->finished; @@ -232,7 +250,8 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) } SerialExecutor* exe = *it; // don't make reentrant calls inside a serialexecutor - if(exe==current_executor && !exe->IsReentrant()) + // or more than the number of concurrent tasks set on a threadpool + if(exe->state_->tasks_running >= exe->state_->max_tasks_running) { continue; } @@ -243,6 +262,7 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); run_task=true; + exe->state_->tasks_running+=1; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); } else { @@ -250,6 +270,7 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) std::move(task.stop_callback)(task.stop_token.Poll()); } } + exe->state_->tasks_running-=1; current_executor=old_exe; if(once_only) @@ -275,43 +296,56 @@ void SerialExecutor::RunLoop() // when all work is done. while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { // first empty us until paused or empty - while (!state_->paused && !state_->task_queue.empty()) { - Task task = std::move(state_->task_queue.front()); - state_->task_queue.pop_front(); - auto last_executor=current_executor; - current_executor=this; - if (!task.stop_token.IsStopRequested()) { + // if we're already running as many tasks as possible then + // we can't run any more until something else drops off the queue + if(state_->tasks_running <= state_->max_tasks_running) + { - std::move(task.callable)(); - } else { - if (task.stop_callback) { - std::move(task.stop_callback)(task.stop_token.Poll()); + while (!state_->paused && !state_->task_queue.empty()) { + Task task = std::move(state_->task_queue.front()); + state_->task_queue.pop_front(); + auto last_executor=current_executor; + current_executor=this; + state_->tasks_running+=1; + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); + } } + state_->tasks_running-=1; + current_executor=last_executor; + } + if(state_->paused || (state_->finished && state_->task_queue.empty())) + { + break; } - current_executor=last_executor; - } - if(state_->paused || state_->finished) - { - break; } // now wait for anything on other executors (unless we're finished in which case it will drop out of // the outer loop - if(!IsReentrant()) - { - // stop runtasks from running our tasks by pausing us during the call - // otherwise things could happen out of order - bool old_paused=state_->paused; - state_->paused=true; - RunTasksOnAllExecutors(true); - state_->paused=old_paused; - }else - { - RunTasksOnAllExecutors(true); - } + RunTasksOnAllExecutors(true); } } +Status ThreadPool::SetCapacity(int threads) +{ + state_->max_tasks_running=threads; + return Status::OK(); +} + +int ThreadPool::GetCapacity() +{ + return state_->max_tasks_running; +} + +int ThreadPool::GetActualCapacity() +{ + return state_->max_tasks_running; +} + + #else //ARROW_DISABLE_THREADING void SerialExecutor::RunLoop() { @@ -355,14 +389,22 @@ void SerialExecutor::RunLoop() { ThreadPool::ThreadPool() { - + // default to max 'concurrency' of 8 + // if threading is disabled + state_->max_tasks_running=8; } Status ThreadPool::Shutdown(bool wait) { + state_->finished=true; if(wait) { RunLoop(); + }else + { + // clear any pending tasks so that we behave + // the same as threadpool on fast shutdown + state_->task_queue.clear(); } return Status::OK(); } @@ -394,7 +436,10 @@ Result> ThreadPool::MakeEternal(int threads) { ThreadPool::~ThreadPool() { - // NOP + // clear threadpool, otherwise ~SerialExecutor will + // run any tasks left (which isn't threadpool behaviour) + state_->task_queue.clear(); + } diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 66b97bf75f7e..df72dfa612ee 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -279,7 +279,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { ~SerialExecutor() override; - int GetCapacity() override { return 1; }; + virtual int GetCapacity() override { return 1; }; bool OwnsThisThread() override; Status SpawnReal(TaskHints hints, FnOnce task, StopToken, StopCallback&&) override; @@ -359,8 +359,13 @@ class ARROW_EXPORT SerialExecutor : public Executor { // the next call. executor->Pause(); }); +#ifdef ARROW_DISABLE_THREADING + // future must run on this thread + next_fut.Wait(); +#else // Borrow this thread and run tasks until the future is finished executor->RunLoop(); +#endif if (!next_fut.is_finished()) { // Not clear this is possible since RunLoop wouldn't generally exit // unless we paused/finished which would imply next_fut has been @@ -422,7 +427,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { } #ifdef ARROW_DISABLE_THREADING - virtual bool IsReentrant(){return false;}; // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; @@ -433,7 +437,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { // without threading we can't tell which executor called the // current process - so we set it in spawning the task static SerialExecutor* current_executor; - #endif // ARROW_DISABLE_THREADING }; @@ -461,12 +464,9 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor // Return the desired number of worker threads. // The actual number of workers may lag a bit before being adjusted to // match this value. - int GetCapacity() override - { - return 1; - } + virtual int GetCapacity() override; - int GetActualCapacity() { return 1; }; + virtual int GetActualCapacity(); bool OwnsThisThread() override { @@ -474,10 +474,12 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor } // Dynamically change the number of worker threads. - // - no op when threading is disabled - Status SetCapacity(int threads){return Status::OK();} + // without threading this is equal to the + // number of tasks that can be running at once + // (inside each other) + Status SetCapacity(int threads); - static int DefaultCapacity(){return 1;} + static int DefaultCapacity(){return 8;} // Shutdown the pool. Once the pool starts shutting down, new tasks // cannot be submitted anymore. @@ -493,7 +495,8 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor protected: static std::shared_ptr MakeCpuThreadPool(); ThreadPool(); - virtual bool IsReentrant(){return true;} + + }; diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index 451378d756f7..2b21b80504a3 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -341,6 +341,7 @@ TEST(SerialExecutor, AsyncGeneratorWithCleanup) { // must run before the terminal item is delivered from the iterator. bool follow_up_ran = false; Iterator iter = + SerialExecutor::IterateGenerator([&](Executor* executor) { return [=, &follow_up_ran]() -> Future { Future end = @@ -583,6 +584,9 @@ TEST_F(TestThreadPool, StressSpawn) { } TEST_F(TestThreadPool, OwnsCurrentThread) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif auto pool = this->MakeThreadPool(30); std::atomic one_failed{false}; @@ -598,8 +602,11 @@ TEST_F(TestThreadPool, OwnsCurrentThread) { ASSERT_FALSE(pool->OwnsThisThread()); ASSERT_FALSE(one_failed); } - TEST_F(TestThreadPool, StressSpawnThreaded) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif + auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_add); } @@ -616,6 +623,9 @@ TEST_F(TestThreadPool, StressSpawnSlow) { } TEST_F(TestThreadPool, StressSpawnSlowThreaded) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_slow_add{/*seconds=*/0.002}); } @@ -627,6 +637,9 @@ TEST_F(TestThreadPool, SpawnWithStopToken) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopToken) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif StopSource stop_source; auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_add, stop_source.token()); @@ -639,6 +652,9 @@ TEST_F(TestThreadPool, SpawnWithStopTokenCancelled) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopTokenCancelled) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif StopSource stop_source; auto pool = this->MakeThreadPool(30); SpawnAddsThreadedAndCancel(pool.get(), 20, 100, task_slow_add{/*seconds=*/0.02}, @@ -660,12 +676,11 @@ TEST_F(TestThreadPool, QuickShutdown) { TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); - // capacity should always be 1, so all these things check for 1 - ASSERT_EQ(pool->GetCapacity(), 1); - ASSERT_EQ(pool->GetActualCapacity(), 1); + ASSERT_EQ(pool->GetCapacity(), 5); + ASSERT_EQ(pool->GetActualCapacity(), 5); ASSERT_OK(pool->SetCapacity(7)); - ASSERT_EQ(pool->GetCapacity(), 1); + ASSERT_EQ(pool->GetCapacity(), 7); } #else// ARROW_DISABLE_THREADING @@ -815,6 +830,10 @@ class TestThreadPoolForkSafety : public TestThreadPool {}; TEST_F(TestThreadPoolForkSafety, Basics) { { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif + // Fork after task submission auto pool = this->MakeThreadPool(3); ASSERT_OK_AND_ASSIGN(auto fut, pool->Submit(add, 4, 5)); @@ -860,7 +879,10 @@ TEST_F(TestThreadPoolForkSafety, Basics) { TEST_F(TestThreadPoolForkSafety, MultipleChildThreads) { // ARROW-15593: race condition in after-fork ThreadPool reinitialization // when SpawnReal() was called from multiple threads in a forked child. - auto run_in_child = [](ThreadPool* pool) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif + auto run_in_child = [](ThreadPool* pool) { const int n_threads = 5; std::vector> futures; std::vector threads; @@ -907,6 +929,9 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { { #ifdef __APPLE__ GTEST_SKIP() << "Nested fork is not supported on macos"; +#endif +#ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; #endif auto pool = this->MakeThreadPool(3); ASSERT_OK_AND_ASSIGN(auto fut, pool->Submit(add, 4, 5)); @@ -941,6 +966,9 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { #endif TEST(TestGlobalThreadPool, Capacity) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif // Sanity check auto pool = GetCpuThreadPool(); int capacity = pool->GetCapacity(); From f7b8de2f41d3d484d16e0740145411ed8c74bcca Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 6 May 2023 07:07:24 +0100 Subject: [PATCH 30/79] async generator test fixes --- cpp/src/arrow/testing/gtest_util.cc | 76 ++++++++++++++++++++++ cpp/src/arrow/util/async_generator_test.cc | 28 +++++++- 2 files changed, 102 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index c3c176ca03f8..c99ca8e08d02 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -1035,7 +1035,64 @@ class GatingTask::Impl : public std::enable_shared_from_this { return unlocked_future_; } + void _WaitForEndOrUnlocked(std::chrono::time_point end_time,arrow::internal::Executor *executor,Future<> future) + { + if(unlocked_) + { + num_finished_++; + future.MarkFinished(Status::OK()); + return; + }else + { + if(std::chrono::steady_clock::now()>end_time) + { + num_finished_++; + future.MarkFinished(Status::Invalid("Task unlock never happened - if threads are disabled you can't wait on gatedtask")); + return; + }else + { + SleepABit(); + auto spawn_status=executor->Spawn([this,end_time,executor,future](){_WaitForEndOrUnlocked(end_time,executor,future);}); + if(!spawn_status.ok()) + { + status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); + } + } + } + } + + Future<> RunTaskFuture() { + num_running_++; + // post the unlock check as a separate task + // otherwise we'll never let anything else run + // so nothing can unlock us + using Clock=std::chrono::steady_clock; + using DurationDouble=std::chrono::duration; + using DurationClock=std::chrono::steady_clock::duration; + + auto start_time = Clock::now(); + std::chrono::duration secs_left=std::chrono::duration(timeout_seconds_); + std::chrono::time_point end_time=std::chrono::time_point_cast(start_time+secs_left); + arrow::internal::Executor *executor=arrow::internal::GetCpuThreadPool(); + Future<> future=Future<>::Make(); + auto spawn_status=executor->Spawn([this,end_time,executor,future](){_WaitForEndOrUnlocked(end_time,executor,future);}); + if(!spawn_status.ok()) + { + status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); + future.MarkFinished(Status::Invalid("")); + } + return future; + } + + void RunTask() { + #ifdef ARROW_DISABLE_THREADING + // can't wait here for anything, so make a future to do the waiting + num_running_++; + auto future=RunTaskFuture(); + future.Wait(); + return; + #else std::unique_lock lk(mx_); num_running_++; running_cv_.notify_all(); @@ -1047,9 +1104,20 @@ class GatingTask::Impl : public std::enable_shared_from_this { " seconds) waiting for the gating task to be unlocked"); } num_finished_++; + #endif } Status WaitForRunning(int count) { +#ifdef ARROW_DISABLE_THREADING + BusyWait(timeout_seconds_,[this, count] { return num_running_ >= count; }); + if(num_running_>=count) + { + return Status::OK(); + }else + { + return Status::Invalid("Timed out waiting for tasks to launch"); + } +#else std::unique_lock lk(mx_); if (running_cv_.wait_for( lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), @@ -1057,6 +1125,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { return Status::OK(); } return Status::Invalid("Timed out waiting for tasks to launch"); +#endif } Status Unlock() { @@ -1066,6 +1135,13 @@ class GatingTask::Impl : public std::enable_shared_from_this { unlocked_cv_.notify_all(); } unlocked_future_.MarkFinished(); +#ifdef ARROW_DISABLE_THREADING + while(num_finished_!=num_running_) + { + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } +#endif + return status_; } diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 37718f743fff..6f9fccafc9a3 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -994,6 +994,9 @@ TEST(TestAsyncUtil, GeneratorIterator) { } TEST(TestAsyncUtil, MakeTransferredGenerator) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; + #endif std::mutex mutex; std::condition_variable cv; std::atomic finished(false); @@ -1486,6 +1489,15 @@ TEST(TestAsyncUtil, ReadaheadFailed) { // should all pass auto source = [&]() -> Future { auto count = counter++; +#ifdef ARROW_DISABLE_THREADING + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything + if (count == 0) { + return gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); + }else{ + return gating_task->AsyncTask().Then([count](){return TestInt(count);}); + } +#else return DeferNotOk(thread_pool->Submit([&, count]() -> Result { gating_task->Task()(); if (count == 0) { @@ -1493,6 +1505,7 @@ TEST(TestAsyncUtil, ReadaheadFailed) { } return TestInt(count); })); +#endif }; auto readahead = MakeReadaheadGenerator(source, 10); auto should_be_invalid = readahead(); @@ -1521,7 +1534,17 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { auto in_flight_gating_task = GatingTask::Make(); auto source = [&]() -> Future { auto count = counter++; - return DeferNotOk(thread_pool->Submit([&, count]() -> Result { + +#ifdef ARROW_DISABLE_THREADING + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything + if (count == 0) { + return failure_gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); + }else{ + return in_flight_gating_task->AsyncTask().Then([](){return TestInt(0);}); + } +#else + return DeferNotOk(thread_pool->Submit([&, count]() -> Result { if (count == 0) { failure_gating_task->Task()(); return Status::Invalid("X"); @@ -1530,7 +1553,8 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { // These are our in-flight tasks return TestInt(0); })); - }; + #endif + }; auto readahead = MakeReadaheadGenerator(source, 10); auto should_be_invalid = readahead(); ASSERT_OK(in_flight_gating_task->WaitForRunning(10)); From 19c9a9a624e2e09f82de7debde83e5a8e4d4322e Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 6 May 2023 10:32:32 +0100 Subject: [PATCH 31/79] test fixes --- cpp/src/arrow/dataset/dataset_writer_test.cc | 9 +++++++++ cpp/src/arrow/util/thread_pool.cc | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index d2480cd482fc..df49953d6052 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -382,6 +382,9 @@ TEST_F(DatasetWriterTestFixture, MinRowGroupBackpressure) { TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { // Use a gated filesystem to queue up many writes behind a file open to make sure the // file isn't opened multiple times. + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; + #endif auto gated_fs = UseGatedFs(); auto dataset_writer = MakeDatasetWriter(); for (int i = 0; i < 10; i++) { @@ -395,6 +398,9 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { // NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; + #endif constexpr int NBATCHES = 6; auto gated_fs = UseGatedFs(); std::vector expected_files; @@ -412,6 +418,9 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { } TEST_F(DatasetWriterTestFixture, MaxOpenFiles) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; + #endif auto gated_fs = UseGatedFs(); std::atomic paused = false; write_options_.max_open_files = 2; diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 955b5d135c0e..9edc7f7e29de 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -416,7 +416,7 @@ void ThreadPool::WaitForIdle() { while(!state_->task_queue.empty()) { - RunLoop(); + RunTasksOnAllExecutors(true); } } From ee62ebcdb148226115a1ac94525841063a2d7d6a Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 6 May 2023 10:45:44 +0100 Subject: [PATCH 32/79] removed asof join benchmark in threads disabled mode --- cpp/src/arrow/acero/CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index 2090629f2fe6..a66261f75e5a 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -246,7 +246,9 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_static) - target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) + if(ARROW_DISABLE_THREADING!=ON) + target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) + endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_static) if(ARROW_BUILD_OPENMP_BENCHMARKS) target_link_libraries(arrow-acero-hash-join-benchmark PUBLIC arrow_acero_static) @@ -255,7 +257,9 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_shared) - target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_shared) + if(ARROW_DISABLE_THREADING!=ON) + target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_shared) + endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_shared) if(ARROW_BUILD_OPENMP_BENCHMARKS) target_link_libraries(arrow-acero-hash-join-benchmark PUBLIC arrow_acero_shared) From c50f415bfb5a3c298afc44031ac5a42dd5052b46 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sat, 6 May 2023 10:48:29 +0100 Subject: [PATCH 33/79] more fixes to makefiles --- cpp/src/arrow/acero/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index a66261f75e5a..1b703dc12f9b 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -168,7 +168,7 @@ add_arrow_acero_test(pivot_longer_node_test SOURCES pivot_longer_node_test.cc # asof_join_node uses std::thread internally # and doesn't use ThreadPool so it will # be broken if threading is turned off -if(ARROW_DISABLE_THREADING!=ON) +if(!ARROW_DISABLE_THREADING) add_arrow_acero_test(asof_join_node_test SOURCES asof_join_node_test.cc test_nodes.cc) endif() @@ -221,7 +221,7 @@ if(ARROW_BUILD_BENCHMARKS) add_arrow_acero_benchmark(project_benchmark SOURCES benchmark_util.cc project_benchmark.cc) -if(ARROW_DISABLE_THREADING!=ON) +if(!ARROW_DISABLE_THREADING) add_arrow_acero_benchmark(asof_join_benchmark SOURCES asof_join_benchmark.cc) endif() @@ -246,7 +246,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_static) - if(ARROW_DISABLE_THREADING!=ON) + if(!ARROW_DISABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_static) @@ -257,7 +257,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_shared) - if(ARROW_DISABLE_THREADING!=ON) + if(!ARROW_DISABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_shared) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_shared) From d4ec8c8ff61310d46aad4261c49c70e42c64a841 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 7 May 2023 07:58:14 +0100 Subject: [PATCH 34/79] test fixes for single threading being slower --- ci/scripts/cpp_test.sh | 6 ++++++ cpp/src/arrow/engine/substrait/serde_test.cc | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/ci/scripts/cpp_test.sh b/ci/scripts/cpp_test.sh index 3acf56bae0fe..616338eb8bc3 100755 --- a/ci/scripts/cpp_test.sh +++ b/ci/scripts/cpp_test.sh @@ -80,6 +80,12 @@ pushd ${build_dir} if [ -z "${PYTHON}" ] && ! which python > /dev/null 2>&1; then export PYTHON="${PYTHON:-python3}" fi +if [[ "${ARROW_DISABLE_THREADING}" == "ON" ]]; then +# if threading is disabled, some tests take longer to run +# but we can get away with running more tests in parallel + ARROW_CTEST_TIMEOUT=${ARROW_CTEST_TIMEOUT:-900} + n_jobs=$((n_jobs*2)) +fi ctest \ --label-regex unittest \ --output-on-failure \ diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc b/cpp/src/arrow/engine/substrait/serde_test.cc index 8ad1b2632e01..71fbbd642ee7 100644 --- a/cpp/src/arrow/engine/substrait/serde_test.cc +++ b/cpp/src/arrow/engine/substrait/serde_test.cc @@ -5261,6 +5261,10 @@ TEST(Substrait, CompoundEmitWithFilter) { } TEST(Substrait, PlanWithExtension) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; + #endif + // This demos an extension relation std::string substrait_json = R"({ "extensionUris": [], @@ -5449,6 +5453,9 @@ TEST(Substrait, PlanWithExtension) { } TEST(Substrait, AsOfJoinDefaultEmit) { + #ifdef ARROW_DISABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; + #endif std::string substrait_json = R"({ "extensionUris": [], "extensions": [], From 85a4b5a5f074e018cbfb520c04549ae4475a03e4 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 7 May 2023 09:49:08 +0100 Subject: [PATCH 35/79] Make no threads test work on Ubuntu-cpp image --- .github/workflows/cpp.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index a506e57f422c..d146406d3bd8 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -64,10 +64,10 @@ jobs: include: - arch: amd64 clang-tools: "14" - image: conda-cpp + image: ubuntu-cpp llvm: "14" runs-on: ubuntu-latest - title: AMD64 Conda C++ no threads + title: AMD64 ubuntu-cpp no threads ubuntu: "22.04" disable_threading: "ON" - arch: amd64 From 1668254b4a482bbf8d92bc8e4f58bd364b92fa17 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 7 May 2023 20:48:45 +0100 Subject: [PATCH 36/79] update cpp_test.sh --- ci/scripts/cpp_test.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/scripts/cpp_test.sh b/ci/scripts/cpp_test.sh index 616338eb8bc3..16d6021de045 100755 --- a/ci/scripts/cpp_test.sh +++ b/ci/scripts/cpp_test.sh @@ -82,9 +82,9 @@ if [ -z "${PYTHON}" ] && ! which python > /dev/null 2>&1; then fi if [[ "${ARROW_DISABLE_THREADING}" == "ON" ]]; then # if threading is disabled, some tests take longer to run -# but we can get away with running more tests in parallel +# but we can get away with running more tests in parallel because we know they wont make loads of threads ARROW_CTEST_TIMEOUT=${ARROW_CTEST_TIMEOUT:-900} - n_jobs=$((n_jobs*2)) + n_jobs=$((n_jobs*4)) fi ctest \ --label-regex unittest \ From ffa1bdb37e2c9b70d98f55ee4d7c99221385cfa8 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Sun, 7 May 2023 20:52:39 +0100 Subject: [PATCH 37/79] Increase timeout for testing --- .github/workflows/cpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index d146406d3bd8..319ad4d97d98 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -57,7 +57,7 @@ jobs: name: ${{ matrix.title }} runs-on: ${{ matrix.runs-on }} if: ${{ !contains(github.event.pull_request.title, 'WIP') }} - timeout-minutes: 75 + timeout-minutes: 120 strategy: fail-fast: false matrix: From bc26756b9354cd9c2f5e5a138a319f7874aebec7 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 9 May 2023 13:33:21 +0100 Subject: [PATCH 38/79] changed to enable_threding --- .github/workflows/cpp.yml | 6 ++--- ci/scripts/cpp_build.sh | 2 +- ci/scripts/cpp_test.sh | 2 +- cmdline-working.txt | 10 ++++++++ cpp/src/arrow/acero/CMakeLists.txt | 8 +++---- cpp/src/arrow/acero/asof_join_node.cc | 2 +- cpp/src/arrow/acero/bloom_filter.cc | 2 +- cpp/src/arrow/acero/bloom_filter_test.cc | 4 ++-- cpp/src/arrow/acero/plan_test.cc | 2 +- cpp/src/arrow/acero/task_util.cc | 2 +- cpp/src/arrow/acero/task_util_test.cc | 4 ++-- cpp/src/arrow/dataset/dataset_writer_test.cc | 6 ++--- cpp/src/arrow/engine/substrait/serde_test.cc | 6 ++--- cpp/src/arrow/testing/gtest_util.cc | 8 +++---- cpp/src/arrow/util/async_generator_test.cc | 6 ++--- cpp/src/arrow/util/config.h.cmake | 2 +- cpp/src/arrow/util/future.cc | 4 ++-- cpp/src/arrow/util/iterator_test.cc | 2 +- cpp/src/arrow/util/task_group.cc | 2 +- cpp/src/arrow/util/thread_pool.cc | 24 ++++++++++---------- cpp/src/arrow/util/thread_pool.h | 14 ++++++------ cpp/src/arrow/util/thread_pool_test.cc | 22 +++++++++--------- 22 files changed, 75 insertions(+), 65 deletions(-) create mode 100644 cmdline-working.txt diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index a506e57f422c..02bf6ee09b63 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -69,7 +69,7 @@ jobs: runs-on: ubuntu-latest title: AMD64 Conda C++ no threads ubuntu: "22.04" - disable_threading: "ON" + enable_threading: "OFF" - arch: amd64 clang-tools: "14" image: conda-cpp @@ -96,7 +96,7 @@ jobs: CLANG_TOOLS: ${{ matrix.clang-tools }} LLVM: ${{ matrix.llvm }} UBUNTU: ${{ matrix.ubuntu }} - ARROW_DISABLE_THREADING: ${{matrix.disable_threading}} + ARROW_ENABLE_THREADING: ${{matrix.enable_threading}} steps: - name: Checkout Arrow uses: actions/checkout@v3 @@ -121,7 +121,7 @@ jobs: run: | sudo sysctl -w kernel.core_pattern="core.%e.%p" ulimit -c unlimited - archery docker run --env ARROW_DISABLE_THREADING=${ARROW_DISABLE_THREADING:-NO} ${{ matrix.image }} + archery docker run --env ARROW_ENABLE_THREADING=${ARROW_ENABLE_THREADING:-ON} ${{ matrix.image }} - name: Docker Push if: success() && github.event_name == 'push' && github.repository == 'apache/arrow' env: diff --git a/ci/scripts/cpp_build.sh b/ci/scripts/cpp_build.sh index 7fa840de18b2..a662469730c3 100755 --- a/ci/scripts/cpp_build.sh +++ b/ci/scripts/cpp_build.sh @@ -128,7 +128,7 @@ cmake \ -DARROW_WITH_UTF8PROC=${ARROW_WITH_UTF8PROC:-ON} \ -DARROW_WITH_ZLIB=${ARROW_WITH_ZLIB:-OFF} \ -DARROW_WITH_ZSTD=${ARROW_WITH_ZSTD:-OFF} \ - -DARROW_DISABLE_THREADING=${ARROW_DISABLE_THREADING:-OFF} \ + -DARROW_ENABLE_THREADING=${ARROW_ENABLE_THREADING:-ON} \ -DAWSSDK_SOURCE=${AWSSDK_SOURCE:-} \ -Dbenchmark_SOURCE=${benchmark_SOURCE:-} \ -DBOOST_SOURCE=${BOOST_SOURCE:-} \ diff --git a/ci/scripts/cpp_test.sh b/ci/scripts/cpp_test.sh index 616338eb8bc3..9a18f2808874 100755 --- a/ci/scripts/cpp_test.sh +++ b/ci/scripts/cpp_test.sh @@ -80,7 +80,7 @@ pushd ${build_dir} if [ -z "${PYTHON}" ] && ! which python > /dev/null 2>&1; then export PYTHON="${PYTHON:-python3}" fi -if [[ "${ARROW_DISABLE_THREADING}" == "ON" ]]; then +if [[ "${ARROW_ENABLE_THREADING}" == "OFF" ]]; then # if threading is disabled, some tests take longer to run # but we can get away with running more tests in parallel ARROW_CTEST_TIMEOUT=${ARROW_CTEST_TIMEOUT:-900} diff --git a/cmdline-working.txt b/cmdline-working.txt new file mode 100644 index 000000000000..5b6dd9d3cc93 --- /dev/null +++ b/cmdline-working.txt @@ -0,0 +1,10 @@ +export CMAKE_TOOLCHAIN_FILE=/home/pszjm2/arrow/Emscripten.cmake + #cmake --preset ninja-release-python ../cpp -DARROW_DEPENDENCY_SOURCE=BUNDLED -DCMAKE_TOOLCHAIN_FILE=/home/pszjm2/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake -D ARROW_JEMALLOC=OFF -D ARROW_MIMALLOC=OFF -D CMAKE_C_BYTE_ORDER=LITTLE_ENDIAN -DCMAKE_INSTALL_OLDINCLUDEDIR=include ARROW_BUILD_SHARED=OFF ARROW_BUILD_STATIC=ON -G "Unix Makefiles" + + cmake --preset ninja-release-python ../cpp -DARROW_DEPENDENCY_SOURCE=BUNDLED -D ARROW_JEMALLOC=OFF -D ARROW_MIMALLOC=OFF -D CMAKE_C_BYTE_ORDER=LITTLE_ENDIAN -DCMAKE_INSTALL_OLDINCLUDEDIR=include -DARROW_BUILD_SHARED=OFF -DARROW_BUILD_STATIC=ON -G "Unix Makefiles" -DARROW_ORC=OFF -DARROW_WITH_BROTLI=OFF -DARROW_FLIGHT=OFF -DARROW_DEPENDENCY_USE_SHARED=OFF -DARROW_SUBSTRAIT=OFF -DARROW_IPC=OFF + + cmake --preset ninja-release-python ../.. -DARROW_FLIGHT=OFF -DARROW_MIMALLOC=OFF -DARROW_JEMALLOC=OFF -DARROW_ENABLE_THREADING=ON -DARROW_DEPENDENCY_SOURCE=BUNDLED -DCMAKE_INSTALL_PREFIX=/home/pszjm2/arrow/dist_x86 + + cmake --preset ninja-release-python ../.. -DARROW_FLIGHT=OFF -DARROW_MIMALLOC=OFF -DARROW_JEMALLOC=OFF -DARROW_ENABLE_THREADING=OFF -DARROW_DEPENDENCY_SOURCE=BUNDLED -D ARROW_TEST=1 -DCMAKE_INSTALL_PREFIX=/home/pszjm2/arrow/dist_x86 + + archery docker run ubuntu-cpp --no-pull -e ARROW_ENABLE_THREADING=ON bash \ No newline at end of file diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index 1b703dc12f9b..8b9d5eab40ce 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -168,7 +168,7 @@ add_arrow_acero_test(pivot_longer_node_test SOURCES pivot_longer_node_test.cc # asof_join_node uses std::thread internally # and doesn't use ThreadPool so it will # be broken if threading is turned off -if(!ARROW_DISABLE_THREADING) +if(ARROW_ENABLE_THREADING) add_arrow_acero_test(asof_join_node_test SOURCES asof_join_node_test.cc test_nodes.cc) endif() @@ -221,7 +221,7 @@ if(ARROW_BUILD_BENCHMARKS) add_arrow_acero_benchmark(project_benchmark SOURCES benchmark_util.cc project_benchmark.cc) -if(!ARROW_DISABLE_THREADING) +if(ARROW_ENABLE_THREADING) add_arrow_acero_benchmark(asof_join_benchmark SOURCES asof_join_benchmark.cc) endif() @@ -246,7 +246,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_static) - if(!ARROW_DISABLE_THREADING) + if(!gig) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_static) @@ -257,7 +257,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_shared) - if(!ARROW_DISABLE_THREADING) + if(ARROW_ENABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_shared) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_shared) diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index 232e3803ef19..f93b9965f438 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -1520,7 +1520,7 @@ class AsofJoinNode : public ExecNode { // Plan has already aborted. Do not start process thread return Status::OK(); } - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING return Status::ExecutionError("ASOF join requires threading enabled"); #endif process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); diff --git a/cpp/src/arrow/acero/bloom_filter.cc b/cpp/src/arrow/acero/bloom_filter.cc index 79a9dd870194..f75a0e333eca 100644 --- a/cpp/src/arrow/acero/bloom_filter.cc +++ b/cpp/src/arrow/acero/bloom_filter.cc @@ -426,7 +426,7 @@ void BloomFilterBuilder_Parallel::CleanUp() { std::unique_ptr BloomFilterBuilder::Make( BloomFilterBuildStrategy strategy) { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING strategy=BloomFilterBuildStrategy::SINGLE_THREADED; #endif switch (strategy) { diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index 4be492126687..1a81777598c8 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -472,7 +472,7 @@ TEST(BloomFilter, Basic) { std::vector strategy; strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); -#ifndef ARROW_DISABLE_THREADING +#ifdef ARROW_ENABLE_THREADING #ifndef ARROW_VALGRIND strategy.push_back(BloomFilterBuildStrategy::PARALLEL); #endif @@ -509,7 +509,7 @@ TEST(BloomFilter, Scaling) { num_build.push_back(4000000); std::vector strategy; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); #else strategy.push_back(BloomFilterBuildStrategy::PARALLEL); diff --git a/cpp/src/arrow/acero/plan_test.cc b/cpp/src/arrow/acero/plan_test.cc index 6594073e5886..02fd201c06be 100644 --- a/cpp/src/arrow/acero/plan_test.cc +++ b/cpp/src/arrow/acero/plan_test.cc @@ -1602,7 +1602,7 @@ TEST(ExecPlan, SourceEnforcesBatchLimit) { } TEST(ExecPlanExecution, SegmentedAggregationWithMultiThreading) { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading enabled"; #endif BatchesWithSchema data; diff --git a/cpp/src/arrow/acero/task_util.cc b/cpp/src/arrow/acero/task_util.cc index a70578f61ac8..1d00f288a4c5 100644 --- a/cpp/src/arrow/acero/task_util.cc +++ b/cpp/src/arrow/acero/task_util.cc @@ -328,7 +328,7 @@ Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) } ARROW_DCHECK(register_finished_); -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING return ExecuteMore(thread_id, 1, true); #else if (use_sync_execution_) { diff --git a/cpp/src/arrow/acero/task_util_test.cc b/cpp/src/arrow/acero/task_util_test.cc index d2fc2fc01752..652445c7b7f6 100644 --- a/cpp/src/arrow/acero/task_util_test.cc +++ b/cpp/src/arrow/acero/task_util_test.cc @@ -102,7 +102,7 @@ TaskScheduler::TaskGroupContinuationImpl MakeFinalContinuation( // concurrently. When all groups in that stage finish the next // stage is started. TEST(TaskScheduler, Stress) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif constexpr int kNumThreads = 8; @@ -181,7 +181,7 @@ TEST(TaskScheduler, Stress) { // the last of its tasks. TEST(TaskScheduler, StressTwo) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index df49953d6052..8358a097acf1 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -382,7 +382,7 @@ TEST_F(DatasetWriterTestFixture, MinRowGroupBackpressure) { TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { // Use a gated filesystem to queue up many writes behind a file open to make sure the // file isn't opened multiple times. - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; #endif auto gated_fs = UseGatedFs(); @@ -398,7 +398,7 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { // NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; #endif constexpr int NBATCHES = 6; @@ -418,7 +418,7 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { } TEST_F(DatasetWriterTestFixture, MaxOpenFiles) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; #endif auto gated_fs = UseGatedFs(); diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc b/cpp/src/arrow/engine/substrait/serde_test.cc index 47487d116db0..cff68c4ee8a8 100644 --- a/cpp/src/arrow/engine/substrait/serde_test.cc +++ b/cpp/src/arrow/engine/substrait/serde_test.cc @@ -4458,7 +4458,7 @@ TEST(Substrait, SetRelationBasic) { } TEST(Substrait, PlanWithAsOfJoinExtension) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "ASOF join requires threading"; #endif // This demos an extension relation @@ -5261,7 +5261,7 @@ TEST(Substrait, CompoundEmitWithFilter) { } TEST(Substrait, PlanWithExtension) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "ASOF join requires threading"; #endif @@ -5453,7 +5453,7 @@ TEST(Substrait, PlanWithExtension) { } TEST(Substrait, AsOfJoinDefaultEmit) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "ASOF join requires threading"; #endif std::string substrait_json = R"({ diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index f32b53f1dda6..e86947fd5c53 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -725,7 +725,7 @@ void TestInitialized(const ArrayData& array) { } void SleepFor(double seconds) { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING std::chrono::duration secs_left=std::chrono::duration(seconds); auto start_time = std::chrono::steady_clock::now(); auto end_time= start_time+secs_left; @@ -1105,7 +1105,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { void RunTask() { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING // can't wait here for anything, so make a future to do the waiting num_running_++; auto future=RunTaskFuture(); @@ -1127,7 +1127,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { } Status WaitForRunning(int count) { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING BusyWait(timeout_seconds_,[this, count] { return num_running_ >= count; }); if(num_running_>=count) { @@ -1154,7 +1154,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { unlocked_cv_.notify_all(); } unlocked_future_.MarkFinished(); -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING while(num_finished_!=num_running_) { arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 6f9fccafc9a3..821bd5122609 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -994,7 +994,7 @@ TEST(TestAsyncUtil, GeneratorIterator) { } TEST(TestAsyncUtil, MakeTransferredGenerator) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif std::mutex mutex; @@ -1489,7 +1489,7 @@ TEST(TestAsyncUtil, ReadaheadFailed) { // should all pass auto source = [&]() -> Future { auto count = counter++; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // if threading is disabled, we can't call Task() as we do below because it will // never return and will block everything if (count == 0) { @@ -1535,7 +1535,7 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { auto source = [&]() -> Future { auto count = counter++; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // if threading is disabled, we can't call Task() as we do below because it will // never return and will block everything if (count == 0) { diff --git a/cpp/src/arrow/util/config.h.cmake b/cpp/src/arrow/util/config.h.cmake index 0b194f32dd1f..bdb2512ef1ad 100644 --- a/cpp/src/arrow/util/config.h.cmake +++ b/cpp/src/arrow/util/config.h.cmake @@ -57,6 +57,6 @@ #cmakedefine ARROW_WITH_MUSL #cmakedefine ARROW_WITH_OPENTELEMETRY #cmakedefine ARROW_WITH_UCX -#cmakedefine ARROW_DISABLE_THREADING +#cmakedefine ARROW_ENABLE_THREADING #cmakedefine GRPCPP_PP_INCLUDE diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index a1a90f4f7460..163f8ef94bcf 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -149,7 +149,7 @@ class ConcreteFutureImpl : public FutureImpl { } void DoWait() { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING while(true) { if(IsFutureFinished(state_)) @@ -165,7 +165,7 @@ class ConcreteFutureImpl : public FutureImpl { } bool DoWait(double seconds) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING auto start = std::chrono::steady_clock::now(); std::chrono::duration fsec=std::chrono::duration(seconds); while(std::chrono::steady_clock::now()-start < fsec) diff --git a/cpp/src/arrow/util/iterator_test.cc b/cpp/src/arrow/util/iterator_test.cc index 4d3d66c7f92b..ba21ddcced20 100644 --- a/cpp/src/arrow/util/iterator_test.cc +++ b/cpp/src/arrow/util/iterator_test.cc @@ -438,7 +438,7 @@ TEST(ReadaheadIterator, Trace) { ASSERT_EQ(values[i], TestInt()); } -#ifndef ARROW_DISABLE_THREADING +#ifdef ARROW_ENABLE_THREADING // Values were all emitted from the same thread, and it's not this thread const auto& thread_ids = tracing->thread_ids(); ASSERT_EQ(thread_ids.size(), 1); diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 9ebd3994672f..efced7fa5006 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -128,7 +128,7 @@ class ThreadedTaskGroup : public TaskGroup { bool ok() const override { return ok_.load(); } Status Finish() override { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING while(!finished_ && nremaining_.load() != 0 ) { arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 9edc7f7e29de..deb6ddb464f1 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -61,13 +61,13 @@ struct SerialExecutor::State { std::thread::id current_thread; bool paused{false}; bool finished{false}; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING int max_tasks_running{1}; int tasks_running{0}; #endif }; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // list of all SerialExecutor objects - as we need to run tasks from all pools at once in Run() std::unordered_set SerialExecutor::all_executors; SerialExecutor* SerialExecutor::current_executor=NULL; @@ -81,14 +81,14 @@ SerialExecutor* SerialExecutor::last_called_executor=NULL; SerialExecutor::SerialExecutor() : state_(std::make_shared()) { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING all_executors.insert(this); state_->max_tasks_running=1; #endif } SerialExecutor::~SerialExecutor() { -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING all_executors.erase(this); #endif auto state = state_; @@ -109,7 +109,7 @@ int SerialExecutor::GetNumTasks() return (int)(state_->task_queue.size()); } -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { #ifdef ARROW_WITH_OPENTELEMETRY @@ -144,7 +144,7 @@ void SerialExecutor::Finish() { } -#else //ARROW_DISABLE_THREADING +#else //ARROW_ENABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { #ifdef ARROW_WITH_OPENTELEMETRY @@ -217,7 +217,7 @@ bool SerialExecutor::OwnsThisThread() { std::lock_guard lk(state_->mutex); return std::this_thread::get_id() == state_->current_thread; } -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { @@ -346,7 +346,7 @@ int ThreadPool::GetActualCapacity() } -#else //ARROW_DISABLE_THREADING +#else //ARROW_ENABLE_THREADING void SerialExecutor::RunLoop() { // This is called from the SerialExecutor's main thread, so the @@ -383,9 +383,9 @@ void SerialExecutor::RunLoop() { } state_->current_thread = {}; } -#endif //ARROW_DISABLE_THREADING +#endif //ARROW_ENABLE_THREADING -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING ThreadPool::ThreadPool() { @@ -443,7 +443,7 @@ ThreadPool::~ThreadPool() } -#else // ARROW_DISABLE_THREADING +#else // ARROW_ENABLE_THREADING struct ThreadPool::State { State() = default; @@ -795,7 +795,7 @@ int ThreadPool::DefaultCapacity() { -#endif //ARROW_DISABLE_THREADING +#endif //ARROW_ENABLE_THREADING // Helper for the singleton pattern std::shared_ptr ThreadPool::MakeCpuThreadPool() { diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index df72dfa612ee..e62703cb02bb 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -359,7 +359,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { // the next call. executor->Pause(); }); -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // future must run on this thread next_fut.Wait(); #else @@ -384,7 +384,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { return Iterator(SerialIterator{std::move(serial_executor), std::move(generator)}); } -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // run loop until everything is done (or one go round loop if once_only=True) // returns true if any tasks were run in the last go round the loop (i.e. if it // returns false, all executors are waiting) @@ -426,7 +426,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { return final_fut; } -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // we have to run tasks from all live executors // during RunLoop if we don't have threading static std::unordered_set all_executors; @@ -437,11 +437,11 @@ class ARROW_EXPORT SerialExecutor : public Executor { // without threading we can't tell which executor called the // current process - so we set it in spawning the task static SerialExecutor* current_executor; -#endif // ARROW_DISABLE_THREADING +#endif // ARROW_ENABLE_THREADING }; -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING // an executor implementation which pretends to be a thread pool but runs everything // on the main thread using a static queue (shared between all thread pools, otherwise // cross-threadpool dependencies will break everything) @@ -500,7 +500,7 @@ class ARROW_EXPORT ThreadPool : public SerialExecutor }; -#else // ARROW_DISABLE_THREADING +#else // ARROW_ENABLE_THREADING /// An Executor implementation spawning tasks in FIFO manner on a fixed-size /// pool of worker threads. @@ -581,7 +581,7 @@ class ARROW_EXPORT ThreadPool : public Executor { State* state_; bool shutdown_on_destroy_; }; -#endif // ARROW_DISABLE_THREADING +#endif // ARROW_ENABLE_THREADING // Return the process-global thread pool for CPU-bound tasks. ARROW_EXPORT ThreadPool* GetCpuThreadPool(); diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index 2b21b80504a3..8fd89fcb3018 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -584,7 +584,7 @@ TEST_F(TestThreadPool, StressSpawn) { } TEST_F(TestThreadPool, OwnsCurrentThread) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif auto pool = this->MakeThreadPool(30); @@ -603,7 +603,7 @@ TEST_F(TestThreadPool, OwnsCurrentThread) { ASSERT_FALSE(one_failed); } TEST_F(TestThreadPool, StressSpawnThreaded) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif @@ -623,7 +623,7 @@ TEST_F(TestThreadPool, StressSpawnSlow) { } TEST_F(TestThreadPool, StressSpawnSlowThreaded) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif auto pool = this->MakeThreadPool(30); @@ -637,7 +637,7 @@ TEST_F(TestThreadPool, SpawnWithStopToken) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopToken) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif StopSource stop_source; @@ -652,7 +652,7 @@ TEST_F(TestThreadPool, SpawnWithStopTokenCancelled) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopTokenCancelled) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif StopSource stop_source; @@ -672,7 +672,7 @@ TEST_F(TestThreadPool, QuickShutdown) { add_tester.CheckNotAllComputed(); } -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); @@ -683,7 +683,7 @@ TEST_F(TestThreadPool, SetCapacity) { ASSERT_EQ(pool->GetCapacity(), 7); } -#else// ARROW_DISABLE_THREADING +#else// ARROW_ENABLE_THREADING TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); @@ -830,7 +830,7 @@ class TestThreadPoolForkSafety : public TestThreadPool {}; TEST_F(TestThreadPoolForkSafety, Basics) { { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif @@ -879,7 +879,7 @@ TEST_F(TestThreadPoolForkSafety, Basics) { TEST_F(TestThreadPoolForkSafety, MultipleChildThreads) { // ARROW-15593: race condition in after-fork ThreadPool reinitialization // when SpawnReal() was called from multiple threads in a forked child. - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif auto run_in_child = [](ThreadPool* pool) { @@ -930,7 +930,7 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { #ifdef __APPLE__ GTEST_SKIP() << "Nested fork is not supported on macos"; #endif -#ifdef ARROW_DISABLE_THREADING +#ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif auto pool = this->MakeThreadPool(3); @@ -966,7 +966,7 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { #endif TEST(TestGlobalThreadPool, Capacity) { - #ifdef ARROW_DISABLE_THREADING + #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif // Sanity check From ef4bf2eb3f12c6f1b113230a5307f833f1e3e163 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 9 May 2023 13:38:40 +0100 Subject: [PATCH 39/79] define threading option in cmake file --- cpp/cmake_modules/DefineOptions.cmake | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cpp/cmake_modules/DefineOptions.cmake b/cpp/cmake_modules/DefineOptions.cmake index e2ad9e7a8b93..d5aa438effbc 100644 --- a/cpp/cmake_modules/DefineOptions.cmake +++ b/cpp/cmake_modules/DefineOptions.cmake @@ -210,6 +210,10 @@ takes precedence over ccache if a storage backend is configured" ON) define_option(ARROW_WITH_MUSL "Whether the system libc is musl or not" OFF) + define_option(ARROW_ENABLE_THREADING "Enable threading in arrow core. If this is disabled, the CPU and I/O threadpools will run tasks on the main thread and not spawn threads." + ON) + + #---------------------------------------------------------------------- set_option_category("Test and benchmark") From 8fdacfeb78172b35768ef30680adf5130ebb7083 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 9 May 2023 14:06:30 +0100 Subject: [PATCH 40/79] disable = enable --- cpp/src/arrow/io/memory_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index d447d9967bdc..683aa80e99ab 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -869,7 +869,7 @@ TEST(CacheOptions, Basics) { check(CacheOptions::MakeFromNetworkMetrics(5, 500, .75, 5), 2.5, 5); } -#ifndef ARROW_DISABLE_THREADING +#ifdef ARROW_ENABLE_THREADING TEST(IOThreadPool, Capacity) { // Simple sanity check auto pool = internal::GetIOThreadPool(); From 406d1f4e3693bc78ef2f40bd5308a13a1133e4bd Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 9 May 2023 14:09:54 +0100 Subject: [PATCH 41/79] line too long fixed --- cpp/cmake_modules/DefineOptions.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/cmake_modules/DefineOptions.cmake b/cpp/cmake_modules/DefineOptions.cmake index d5aa438effbc..2bde94e62a39 100644 --- a/cpp/cmake_modules/DefineOptions.cmake +++ b/cpp/cmake_modules/DefineOptions.cmake @@ -210,7 +210,7 @@ takes precedence over ccache if a storage backend is configured" ON) define_option(ARROW_WITH_MUSL "Whether the system libc is musl or not" OFF) - define_option(ARROW_ENABLE_THREADING "Enable threading in arrow core. If this is disabled, the CPU and I/O threadpools will run tasks on the main thread and not spawn threads." + define_option(ARROW_ENABLE_THREADING "Enable threading in arrow core. " ON) From e57b31351d6cbec1bab83ebb3118e50bd2e696a1 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 10 May 2023 06:38:44 +0100 Subject: [PATCH 42/79] Delete cmdline-working.txt removed debug file --- cmdline-working.txt | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 cmdline-working.txt diff --git a/cmdline-working.txt b/cmdline-working.txt deleted file mode 100644 index 5b6dd9d3cc93..000000000000 --- a/cmdline-working.txt +++ /dev/null @@ -1,10 +0,0 @@ -export CMAKE_TOOLCHAIN_FILE=/home/pszjm2/arrow/Emscripten.cmake - #cmake --preset ninja-release-python ../cpp -DARROW_DEPENDENCY_SOURCE=BUNDLED -DCMAKE_TOOLCHAIN_FILE=/home/pszjm2/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake -D ARROW_JEMALLOC=OFF -D ARROW_MIMALLOC=OFF -D CMAKE_C_BYTE_ORDER=LITTLE_ENDIAN -DCMAKE_INSTALL_OLDINCLUDEDIR=include ARROW_BUILD_SHARED=OFF ARROW_BUILD_STATIC=ON -G "Unix Makefiles" - - cmake --preset ninja-release-python ../cpp -DARROW_DEPENDENCY_SOURCE=BUNDLED -D ARROW_JEMALLOC=OFF -D ARROW_MIMALLOC=OFF -D CMAKE_C_BYTE_ORDER=LITTLE_ENDIAN -DCMAKE_INSTALL_OLDINCLUDEDIR=include -DARROW_BUILD_SHARED=OFF -DARROW_BUILD_STATIC=ON -G "Unix Makefiles" -DARROW_ORC=OFF -DARROW_WITH_BROTLI=OFF -DARROW_FLIGHT=OFF -DARROW_DEPENDENCY_USE_SHARED=OFF -DARROW_SUBSTRAIT=OFF -DARROW_IPC=OFF - - cmake --preset ninja-release-python ../.. -DARROW_FLIGHT=OFF -DARROW_MIMALLOC=OFF -DARROW_JEMALLOC=OFF -DARROW_ENABLE_THREADING=ON -DARROW_DEPENDENCY_SOURCE=BUNDLED -DCMAKE_INSTALL_PREFIX=/home/pszjm2/arrow/dist_x86 - - cmake --preset ninja-release-python ../.. -DARROW_FLIGHT=OFF -DARROW_MIMALLOC=OFF -DARROW_JEMALLOC=OFF -DARROW_ENABLE_THREADING=OFF -DARROW_DEPENDENCY_SOURCE=BUNDLED -D ARROW_TEST=1 -DCMAKE_INSTALL_PREFIX=/home/pszjm2/arrow/dist_x86 - - archery docker run ubuntu-cpp --no-pull -e ARROW_ENABLE_THREADING=ON bash \ No newline at end of file From b46ef4fe9862d5e6e6a742fba419c4425f2f0509 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 10 May 2023 06:44:14 +0100 Subject: [PATCH 43/79] Update cpp/src/arrow/acero/bloom_filter_test.cc Co-authored-by: Antoine Pitrou --- cpp/src/arrow/acero/bloom_filter_test.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index 1a81777598c8..c5129e187a98 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -472,10 +472,8 @@ TEST(BloomFilter, Basic) { std::vector strategy; strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); -#ifdef ARROW_ENABLE_THREADING -#ifndef ARROW_VALGRIND +#if defined(ARROW_ENABLE_THREADING) && !defined(ARROW_VALGRIND) strategy.push_back(BloomFilterBuildStrategy::PARALLEL); -#endif #endif static constexpr int64_t min_rows_for_large = 2 * 1024 * 1024; From 87060221e8f23091e75bfa47a3bf5798529e88da Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 10 May 2023 06:55:30 +0100 Subject: [PATCH 44/79] review fixes --- cpp/cmake_modules/DefineOptions.cmake | 2 +- cpp/src/arrow/acero/CMakeLists.txt | 2 +- cpp/src/arrow/acero/asof_join_node.cc | 20 +++++++++++--------- cpp/src/arrow/acero/asof_join_node_test.cc | 2 +- cpp/src/arrow/acero/bloom_filter.cc | 2 +- cpp/src/arrow/acero/task_util.cc | 8 ++++---- cpp/src/arrow/acero/task_util_test.cc | 3 --- cpp/src/arrow/util/config.h.cmake | 2 +- dev/tasks/tasks.yml | 9 +++++++++ 9 files changed, 29 insertions(+), 21 deletions(-) diff --git a/cpp/cmake_modules/DefineOptions.cmake b/cpp/cmake_modules/DefineOptions.cmake index 2bde94e62a39..066844119535 100644 --- a/cpp/cmake_modules/DefineOptions.cmake +++ b/cpp/cmake_modules/DefineOptions.cmake @@ -210,7 +210,7 @@ takes precedence over ccache if a storage backend is configured" ON) define_option(ARROW_WITH_MUSL "Whether the system libc is musl or not" OFF) - define_option(ARROW_ENABLE_THREADING "Enable threading in arrow core. " + define_option(ARROW_ENABLE_THREADING "Enable threading in Arrow core." ON) diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index 8b9d5eab40ce..b1281c7d864c 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -246,7 +246,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_static) - if(!gig) + if(ARROW_ENABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_static) diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index f93b9965f438..b449e20606a9 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -1514,17 +1514,19 @@ class AsofJoinNode : public ExecNode { } Status StartProducing() override { - ARROW_ASSIGN_OR_RAISE(process_task_, plan_->query_context()->BeginExternalTask( - "AsofJoinNode::ProcessThread")); - if (!process_task_.is_valid()) { - // Plan has already aborted. Do not start process thread - return Status::OK(); - } #ifndef ARROW_ENABLE_THREADING - return Status::ExecutionError("ASOF join requires threading enabled"); + return Status::NotImplemented("ASOF join requires threading enabled"); + #else + + ARROW_ASSIGN_OR_RAISE(process_task_, plan_->query_context()->BeginExternalTask( + "AsofJoinNode::ProcessThread")); + if (!process_task_.is_valid()) { + // Plan has already aborted. Do not start process thread + return Status::OK(); + } + process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); + return Status::OK(); #endif - process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); - return Status::OK(); } void PauseProducing(ExecNode* output, int32_t counter) override {} diff --git a/cpp/src/arrow/acero/asof_join_node_test.cc b/cpp/src/arrow/acero/asof_join_node_test.cc index a3a2bc314610..730a82fb097d 100644 --- a/cpp/src/arrow/acero/asof_join_node_test.cc +++ b/cpp/src/arrow/acero/asof_join_node_test.cc @@ -1380,7 +1380,7 @@ T GetEnvValue(const std::string& var, T default_value) { } // namespace TEST(AsofJoinTest, BackpressureWithBatchesGen) { - int num_batches = GetEnvValue("ARROW_BACKPRESSURE_DEMO_NUM_BATCHES", 2); + int num_batches = GetEnvValue("ARROW_BACKPRESSURE_DEMO_NUM_BATCHES", 10); int batch_size = GetEnvValue("ARROW_BACKPRESSURE_DEMO_BATCH_SIZE", 1); return TestBackpressure(MakeIntegerBatchGenForTest, num_batches, batch_size, /*fast_delay=*/0.001, /*slow_delay=*/0.01); diff --git a/cpp/src/arrow/acero/bloom_filter.cc b/cpp/src/arrow/acero/bloom_filter.cc index f75a0e333eca..b3aeda9c2da6 100644 --- a/cpp/src/arrow/acero/bloom_filter.cc +++ b/cpp/src/arrow/acero/bloom_filter.cc @@ -427,7 +427,7 @@ void BloomFilterBuilder_Parallel::CleanUp() { std::unique_ptr BloomFilterBuilder::Make( BloomFilterBuildStrategy strategy) { #ifndef ARROW_ENABLE_THREADING - strategy=BloomFilterBuildStrategy::SINGLE_THREADED; + strategy = BloomFilterBuildStrategy::SINGLE_THREADED; #endif switch (strategy) { case BloomFilterBuildStrategy::SINGLE_THREADED: { diff --git a/cpp/src/arrow/acero/task_util.cc b/cpp/src/arrow/acero/task_util.cc index 1d00f288a4c5..99ca707bfbee 100644 --- a/cpp/src/arrow/acero/task_util.cc +++ b/cpp/src/arrow/acero/task_util.cc @@ -316,7 +316,11 @@ Status TaskSchedulerImpl::StartScheduling(size_t thread_id, ScheduleImpl schedul int num_concurrent_tasks, bool use_sync_execution) { schedule_impl_ = std::move(schedule_impl); +#ifdef ARROW_ENABLE_THREADING use_sync_execution_ = use_sync_execution; +#else + use_sync_execution_ = true; +#endif num_concurrent_tasks_ = num_concurrent_tasks; num_tasks_to_schedule_.value += num_concurrent_tasks; return ScheduleMore(thread_id); @@ -328,13 +332,9 @@ Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) } ARROW_DCHECK(register_finished_); -#ifndef ARROW_ENABLE_THREADING - return ExecuteMore(thread_id, 1, true); -#else if (use_sync_execution_) { return ExecuteMore(thread_id, 1, true); } -#endif int num_new_tasks = num_tasks_finished; for (;;) { diff --git a/cpp/src/arrow/acero/task_util_test.cc b/cpp/src/arrow/acero/task_util_test.cc index 652445c7b7f6..b209c85bb27d 100644 --- a/cpp/src/arrow/acero/task_util_test.cc +++ b/cpp/src/arrow/acero/task_util_test.cc @@ -180,12 +180,9 @@ TEST(TaskScheduler, Stress) { // thread starts a task group while another thread is finishing // the last of its tasks. TEST(TaskScheduler, StressTwo) { - #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif - - constexpr int kNumThreads = 16; constexpr int kNumGroups = 8; constexpr int kTasksPerGroup = 1; diff --git a/cpp/src/arrow/util/config.h.cmake b/cpp/src/arrow/util/config.h.cmake index bdb2512ef1ad..a92471cf8777 100644 --- a/cpp/src/arrow/util/config.h.cmake +++ b/cpp/src/arrow/util/config.h.cmake @@ -51,12 +51,12 @@ #cmakedefine ARROW_PARQUET #cmakedefine ARROW_SUBSTRAIT +#cmakedefine ARROW_ENABLE_THREADING #cmakedefine ARROW_GCS #cmakedefine ARROW_S3 #cmakedefine ARROW_USE_NATIVE_INT128 #cmakedefine ARROW_WITH_MUSL #cmakedefine ARROW_WITH_OPENTELEMETRY #cmakedefine ARROW_WITH_UCX -#cmakedefine ARROW_ENABLE_THREADING #cmakedefine GRPCPP_PP_INCLUDE diff --git a/dev/tasks/tasks.yml b/dev/tasks/tasks.yml index 6d07c65b46ec..103c11acc465 100644 --- a/dev/tasks/tasks.yml +++ b/dev/tasks/tasks.yml @@ -1162,6 +1162,15 @@ tasks: image: ubuntu-cpp {% endfor %} + test-ubuntu-22.04-cpp-no-threading: + ci: github + template: docker-tests/github.linux.yml + params: + env: + UBUNTU: 22.04 + flags: "-e ARROW_ENABLE_THREADING=OFF" + image: ubuntu-cpp + test-ubuntu-20.04-cpp-thread-sanitizer: ci: github template: docker-tests/github.linux.yml From 84a8485c5b3a7241037f95055d75874b86706b43 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 10 May 2023 06:56:55 +0100 Subject: [PATCH 45/79] reverted github workflow --- .github/workflows/cpp.yml | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index 85976be9c84c..b5631ca3bd82 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -57,19 +57,11 @@ jobs: name: ${{ matrix.title }} runs-on: ${{ matrix.runs-on }} if: ${{ !contains(github.event.pull_request.title, 'WIP') }} - timeout-minutes: 120 + timeout-minutes: 75 strategy: fail-fast: false matrix: include: - - arch: amd64 - clang-tools: "14" - image: ubuntu-cpp - llvm: "14" - runs-on: ubuntu-latest - title: AMD64 ubuntu-cpp no threads - ubuntu: "22.04" - enable_threading: "OFF" - arch: amd64 clang-tools: "14" image: conda-cpp @@ -96,7 +88,6 @@ jobs: CLANG_TOOLS: ${{ matrix.clang-tools }} LLVM: ${{ matrix.llvm }} UBUNTU: ${{ matrix.ubuntu }} - ARROW_ENABLE_THREADING: ${{matrix.enable_threading}} steps: - name: Checkout Arrow uses: actions/checkout@v3 @@ -121,7 +112,7 @@ jobs: run: | sudo sysctl -w kernel.core_pattern="core.%e.%p" ulimit -c unlimited - archery docker run --env ARROW_ENABLE_THREADING=${ARROW_ENABLE_THREADING:-ON} ${{ matrix.image }} + archery docker run ${{ matrix.image }} - name: Docker Push if: success() && github.event_name == 'push' && github.repository == 'apache/arrow' env: From 35575143621aea47a2d769210349efac4a226393 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 11:30:54 +0100 Subject: [PATCH 46/79] lint fixes --- ci/scripts/cpp_build.sh | 2 +- ci/scripts/cpp_test.sh | 6 ------ cpp/cmake_modules/ThirdpartyToolchain.cmake | 4 ++-- cpp/src/arrow/acero/asof_join_node.cc | 3 +-- cpp/src/arrow/acero/bloom_filter_test.cc | 6 +++--- cpp/src/arrow/acero/plan_test.cc | 6 +++--- cpp/src/arrow/acero/task_util.cc | 1 + cpp/src/arrow/acero/task_util.h | 1 + 8 files changed, 12 insertions(+), 17 deletions(-) diff --git a/ci/scripts/cpp_build.sh b/ci/scripts/cpp_build.sh index b98252cb9b4b..5fb5b2c4c6c0 100755 --- a/ci/scripts/cpp_build.sh +++ b/ci/scripts/cpp_build.sh @@ -86,6 +86,7 @@ cmake \ -DARROW_CXXFLAGS=${ARROW_CXXFLAGS:-} \ -DARROW_DATASET=${ARROW_DATASET:-ON} \ -DARROW_DEPENDENCY_SOURCE=${ARROW_DEPENDENCY_SOURCE:-AUTO} \ + -DARROW_ENABLE_THREADING=${ARROW_ENABLE_THREADING:-ON} \ -DARROW_ENABLE_TIMING_TESTS=${ARROW_ENABLE_TIMING_TESTS:-ON} \ -DARROW_EXTRA_ERROR_CONTEXT=${ARROW_EXTRA_ERROR_CONTEXT:-OFF} \ -DARROW_FILESYSTEM=${ARROW_FILESYSTEM:-ON} \ @@ -129,7 +130,6 @@ cmake \ -DARROW_WITH_UTF8PROC=${ARROW_WITH_UTF8PROC:-ON} \ -DARROW_WITH_ZLIB=${ARROW_WITH_ZLIB:-OFF} \ -DARROW_WITH_ZSTD=${ARROW_WITH_ZSTD:-OFF} \ - -DARROW_ENABLE_THREADING=${ARROW_ENABLE_THREADING:-ON} \ -DAWSSDK_SOURCE=${AWSSDK_SOURCE:-} \ -Dbenchmark_SOURCE=${benchmark_SOURCE:-} \ -DBOOST_SOURCE=${BOOST_SOURCE:-} \ diff --git a/ci/scripts/cpp_test.sh b/ci/scripts/cpp_test.sh index 4a01cd997cad..3acf56bae0fe 100755 --- a/ci/scripts/cpp_test.sh +++ b/ci/scripts/cpp_test.sh @@ -80,12 +80,6 @@ pushd ${build_dir} if [ -z "${PYTHON}" ] && ! which python > /dev/null 2>&1; then export PYTHON="${PYTHON:-python3}" fi -if [[ "${ARROW_ENABLE_THREADING}" == "OFF" ]]; then -# if threading is disabled, some tests take longer to run -# but we can get away with running more tests in parallel because we know they wont make loads of threads - ARROW_CTEST_TIMEOUT=${ARROW_CTEST_TIMEOUT:-900} - n_jobs=$((n_jobs*4)) -fi ctest \ --label-regex unittest \ --output-on-failure \ diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake index 6761cde54025..a67b87e5a3e1 100644 --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -2325,7 +2325,7 @@ macro(build_benchmark) endmacro() if(ARROW_BUILD_BENCHMARKS) - set(BENCHMARK_REQUIRED_VERSION 1.6.1) + set(BENCHMARK_REQUIRED_VERSION 1.6.0) resolve_dependency(benchmark REQUIRED_VERSION ${BENCHMARK_REQUIRED_VERSION} @@ -5190,4 +5190,4 @@ message(STATUS "All bundled static libraries: ${ARROW_BUNDLED_STATIC_LIBS}") configure_file("src/arrow/util/config.h.cmake" "src/arrow/util/config.h" ESCAPE_QUOTES) install(FILES "${ARROW_BINARY_DIR}/src/arrow/util/config.h" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/arrow/util") \ No newline at end of file + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/arrow/util") diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index b449e20606a9..f1b8916706b4 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -1516,7 +1516,7 @@ class AsofJoinNode : public ExecNode { Status StartProducing() override { #ifndef ARROW_ENABLE_THREADING return Status::NotImplemented("ASOF join requires threading enabled"); - #else + #endif ARROW_ASSIGN_OR_RAISE(process_task_, plan_->query_context()->BeginExternalTask( "AsofJoinNode::ProcessThread")); @@ -1526,7 +1526,6 @@ class AsofJoinNode : public ExecNode { } process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); return Status::OK(); - #endif } void PauseProducing(ExecNode* output, int32_t counter) override {} diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index c5129e187a98..dd1644580e1c 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -507,10 +507,10 @@ TEST(BloomFilter, Scaling) { num_build.push_back(4000000); std::vector strategy; -#ifndef ARROW_ENABLE_THREADING - strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); -#else +#ifdef ARROW_ENABLE_THREADING strategy.push_back(BloomFilterBuildStrategy::PARALLEL); +#else + strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); #endif for (bool use_avx2 : {false, true}) { diff --git a/cpp/src/arrow/acero/plan_test.cc b/cpp/src/arrow/acero/plan_test.cc index 02fd201c06be..d98c537158c3 100644 --- a/cpp/src/arrow/acero/plan_test.cc +++ b/cpp/src/arrow/acero/plan_test.cc @@ -985,9 +985,9 @@ TEST(ExecPlanExecution, StressSourceSinkStopped) { EXPECT_THAT(first_batch_fut, Finishes(ResultWith(Optional(random_data.batches[0])))); } - - plan->StopProducing(); - Future<> finished = plan->finished(); + + plan->StopProducing(); + Future<> finished = plan->finished(); CheckFinishesCancelledOrOk(plan->finished()); } } diff --git a/cpp/src/arrow/acero/task_util.cc b/cpp/src/arrow/acero/task_util.cc index 99ca707bfbee..c68b100a8076 100644 --- a/cpp/src/arrow/acero/task_util.cc +++ b/cpp/src/arrow/acero/task_util.cc @@ -332,6 +332,7 @@ Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) } ARROW_DCHECK(register_finished_); + if (use_sync_execution_) { return ExecuteMore(thread_id, 1, true); } diff --git a/cpp/src/arrow/acero/task_util.h b/cpp/src/arrow/acero/task_util.h index bc19396bd243..867b193b4655 100644 --- a/cpp/src/arrow/acero/task_util.h +++ b/cpp/src/arrow/acero/task_util.h @@ -25,6 +25,7 @@ #include "arrow/acero/visibility.h" #include "arrow/status.h" #include "arrow/util/logging.h" +#include "arrow/util/config.h" namespace arrow { namespace acero { From 17c6b181782e8b5c93f542302623670127c9969e Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 11:48:26 +0100 Subject: [PATCH 47/79] flipped #ifndef #else --- cpp/src/arrow/testing/gtest_util.cc | 54 ++-- cpp/src/arrow/util/async_generator_test.cc | 36 +-- cpp/src/arrow/util/future.cc | 24 +- cpp/src/arrow/util/task_group.cc | 14 +- cpp/src/arrow/util/thread_pool.cc | 296 ++++++++++----------- cpp/src/arrow/util/thread_pool.h | 127 +++++---- cpp/src/arrow/util/thread_pool_test.cc | 24 +- 7 files changed, 285 insertions(+), 290 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index e86947fd5c53..7e1af70e5532 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -725,7 +725,10 @@ void TestInitialized(const ArrayData& array) { } void SleepFor(double seconds) { -#ifndef ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING + std::this_thread::sleep_for( + std::chrono::nanoseconds(static_cast(seconds * 1e9))); +#else std::chrono::duration secs_left=std::chrono::duration(seconds); auto start_time = std::chrono::steady_clock::now(); auto end_time= start_time+secs_left; @@ -741,9 +744,6 @@ void SleepFor(double seconds) { } // run one task then check time } -#else - std::this_thread::sleep_for( - std::chrono::nanoseconds(static_cast(seconds * 1e9))); #endif } @@ -1105,38 +1105,29 @@ class GatingTask::Impl : public std::enable_shared_from_this { void RunTask() { - #ifndef ARROW_ENABLE_THREADING + #ifdef ARROW_ENABLE_THREADING + std::unique_lock lk(mx_); + num_running_++; + running_cv_.notify_all(); + if (!unlocked_cv_.wait_for( + lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), + [this] { return unlocked_; })) { + status_ &= Status::Invalid("Timed out (" + std::to_string(timeout_seconds_) + "," + + std::to_string(unlocked_) + + " seconds) waiting for the gating task to be unlocked"); + } + num_finished_++; + #else // can't wait here for anything, so make a future to do the waiting num_running_++; auto future=RunTaskFuture(); future.Wait(); return; - #else - std::unique_lock lk(mx_); - num_running_++; - running_cv_.notify_all(); - if (!unlocked_cv_.wait_for( - lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), - [this] { return unlocked_; })) { - status_ &= Status::Invalid("Timed out (" + std::to_string(timeout_seconds_) + "," + - std::to_string(unlocked_) + - " seconds) waiting for the gating task to be unlocked"); - } - num_finished_++; #endif } Status WaitForRunning(int count) { -#ifndef ARROW_ENABLE_THREADING - BusyWait(timeout_seconds_,[this, count] { return num_running_ >= count; }); - if(num_running_>=count) - { - return Status::OK(); - }else - { - return Status::Invalid("Timed out waiting for tasks to launch"); - } -#else +#ifdef ARROW_ENABLE_THREADING std::unique_lock lk(mx_); if (running_cv_.wait_for( lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), @@ -1144,6 +1135,15 @@ class GatingTask::Impl : public std::enable_shared_from_this { return Status::OK(); } return Status::Invalid("Timed out waiting for tasks to launch"); +#else + BusyWait(timeout_seconds_,[this, count] { return num_running_ >= count; }); + if(num_running_>=count) + { + return Status::OK(); + }else + { + return Status::Invalid("Timed out waiting for tasks to launch"); + } #endif } diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 821bd5122609..97dbe2c0fbdf 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -1489,15 +1489,7 @@ TEST(TestAsyncUtil, ReadaheadFailed) { // should all pass auto source = [&]() -> Future { auto count = counter++; -#ifndef ARROW_ENABLE_THREADING - // if threading is disabled, we can't call Task() as we do below because it will - // never return and will block everything - if (count == 0) { - return gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); - }else{ - return gating_task->AsyncTask().Then([count](){return TestInt(count);}); - } -#else +#ifdef ARROW_ENABLE_THREADING return DeferNotOk(thread_pool->Submit([&, count]() -> Result { gating_task->Task()(); if (count == 0) { @@ -1505,6 +1497,14 @@ TEST(TestAsyncUtil, ReadaheadFailed) { } return TestInt(count); })); +#else + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything + if (count == 0) { + return gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); + }else{ + return gating_task->AsyncTask().Then([count](){return TestInt(count);}); + } #endif }; auto readahead = MakeReadaheadGenerator(source, 10); @@ -1535,15 +1535,7 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { auto source = [&]() -> Future { auto count = counter++; -#ifndef ARROW_ENABLE_THREADING - // if threading is disabled, we can't call Task() as we do below because it will - // never return and will block everything - if (count == 0) { - return failure_gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); - }else{ - return in_flight_gating_task->AsyncTask().Then([](){return TestInt(0);}); - } -#else +#ifdef ARROW_ENABLE_THREADING return DeferNotOk(thread_pool->Submit([&, count]() -> Result { if (count == 0) { failure_gating_task->Task()(); @@ -1553,6 +1545,14 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { // These are our in-flight tasks return TestInt(0); })); +#else + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything + if (count == 0) { + return failure_gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); + }else{ + return in_flight_gating_task->AsyncTask().Then([](){return TestInt(0);}); + } #endif }; auto readahead = MakeReadaheadGenerator(source, 10); diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 163f8ef94bcf..d1ee497c4f2f 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -149,7 +149,10 @@ class ConcreteFutureImpl : public FutureImpl { } void DoWait() { - #ifndef ARROW_ENABLE_THREADING + #ifdef ARROW_ENABLE_THREADING + std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { return IsFutureFinished(state_); }); + #else while(true) { if(IsFutureFinished(state_)) @@ -158,14 +161,17 @@ class ConcreteFutureImpl : public FutureImpl { } arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); } - #else - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { return IsFutureFinished(state_); }); #endif } bool DoWait(double seconds) { - #ifndef ARROW_ENABLE_THREADING + #ifdef ARROW_ENABLE_THREADING + std::unique_lock lock(mutex_); + + cv_.wait_for(lock, std::chrono::duration(seconds), + [this] { return IsFutureFinished(state_); }); + return IsFutureFinished(state_); + #else auto start = std::chrono::steady_clock::now(); std::chrono::duration fsec=std::chrono::duration(seconds); while(std::chrono::steady_clock::now()-start < fsec) @@ -178,14 +184,6 @@ class ConcreteFutureImpl : public FutureImpl { arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); } return IsFutureFinished(state_); - - #else - - std::unique_lock lock(mutex_); - - cv_.wait_for(lock, std::chrono::duration(seconds), - [this] { return IsFutureFinished(state_); }); - return IsFutureFinished(state_); #endif } diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index efced7fa5006..c36cad32ffb3 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -128,19 +128,19 @@ class ThreadedTaskGroup : public TaskGroup { bool ok() const override { return ok_.load(); } Status Finish() override { - #ifndef ARROW_ENABLE_THREADING - while(!finished_ && nremaining_.load() != 0 ) - { - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); - } - finished_ = true; - #else + #ifdef ARROW_ENABLE_THREADING std::unique_lock lock(mutex_); if (!finished_) { cv_.wait(lock, [&]() { return nremaining_.load() == 0; }); // Current tasks may start other tasks, so only set this when done finished_ = true; } + #else + while(!finished_ && nremaining_.load() != 0 ) + { + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } + finished_ = true; #endif return status_; } diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index deb6ddb464f1..fda868bf7bbd 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -109,42 +109,7 @@ int SerialExecutor::GetNumTasks() return (int)(state_->task_queue.size()); } -#ifndef ARROW_ENABLE_THREADING -Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, - StopToken stop_token, StopCallback&& stop_callback) { -#ifdef ARROW_WITH_OPENTELEMETRY - // Wrap the task to propagate a parent tracing span to it - // XXX should there be a generic utility in tracing_internal.h for this? - task = [func = std::move(task), - active_span = - ::arrow::internal::tracing::GetTracer()->GetCurrentSpan()]() mutable { - auto scope = ::arrow::internal::tracing::GetTracer()->WithActiveSpan(active_span); - std::move(func)(); - }; -#endif// ARROW_WITH_OPENTELEMETRY - - if (state_->finished) { - return Status::Invalid( - "Attempt to schedule a task on a serial executor that has already finished or " - "been abandoned"); - } - - state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); - - return Status::OK(); -} - -void SerialExecutor::Finish() { - auto state = state_; - { - state->finished = true; - } - // empty any tasks from the loop on finish - RunLoop(); -} - - -#else //ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { #ifdef ARROW_WITH_OPENTELEMETRY @@ -188,7 +153,41 @@ void SerialExecutor::Finish() { state->wait_for_tasks.notify_one(); } -#endif +#else // ARROW_ENABLE_THREADING +Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, + StopToken stop_token, StopCallback&& stop_callback) { +#ifdef ARROW_WITH_OPENTELEMETRY + // Wrap the task to propagate a parent tracing span to it + // XXX should there be a generic utility in tracing_internal.h for this? + task = [func = std::move(task), + active_span = + ::arrow::internal::tracing::GetTracer()->GetCurrentSpan()]() mutable { + auto scope = ::arrow::internal::tracing::GetTracer()->WithActiveSpan(active_span); + std::move(func)(); + }; +#endif// ARROW_WITH_OPENTELEMETRY + + if (state_->finished) { + return Status::Invalid( + "Attempt to schedule a task on a serial executor that has already finished or " + "been abandoned"); + } + + state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); + + return Status::OK(); +} + +void SerialExecutor::Finish() { + auto state = state_; + { + state->finished = true; + } + // empty any tasks from the loop on finish + RunLoop(); +} + +#endif // ARROW_ENABLE_THREADING void SerialExecutor::Pause() { // Same comment as SpawnReal above auto state = state_; @@ -217,8 +216,46 @@ bool SerialExecutor::OwnsThisThread() { std::lock_guard lk(state_->mutex); return std::this_thread::get_id() == state_->current_thread; } -#ifndef ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING + + +void SerialExecutor::RunLoop() { + // This is called from the SerialExecutor's main thread, so the + // state is guaranteed to be kept alive. + std::unique_lock lk(state_->mutex); + state_->current_thread = std::this_thread::get_id(); + // If paused we break out immediately. If finished we only break out + // when all work is done. + while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { + // The inner loop is to check if we need to sleep (e.g. while waiting on some + // async task to finish from another thread pool). We still need to check paused + // because sometimes we will pause even with work leftover when processing + // an async generator + while (!state_->paused && !state_->task_queue.empty()) { + Task task = std::move(state_->task_queue.front()); + state_->task_queue.pop_front(); + lk.unlock(); + if (!task.stop_token.IsStopRequested()) { + std::move(task.callable)(); + } else { + if (task.stop_callback) { + std::move(task.stop_callback)(task.stop_token.Poll()); + } + // Can't break here because there may be cleanup tasks down the chain we still + // need to run. + } + lk.lock(); + } + // In this case we must be waiting on work from external (e.g. I/O) executors. Wait + // for tasks to arrive (typically via transferred futures). + state_->wait_for_tasks.wait(lk, [&] { + return state_->paused || state_->finished || !state_->task_queue.empty(); + }); + } + state_->current_thread = {}; +} +#else // ARROW_ENABLE_THREADING bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { if(last_called_executor!=NULL && all_executors.count(last_called_executor)==0) @@ -328,122 +365,12 @@ void SerialExecutor::RunLoop() } } - -Status ThreadPool::SetCapacity(int threads) -{ - state_->max_tasks_running=threads; - return Status::OK(); -} - -int ThreadPool::GetCapacity() -{ - return state_->max_tasks_running; -} - -int ThreadPool::GetActualCapacity() -{ - return state_->max_tasks_running; -} - - -#else //ARROW_ENABLE_THREADING - -void SerialExecutor::RunLoop() { - // This is called from the SerialExecutor's main thread, so the - // state is guaranteed to be kept alive. - std::unique_lock lk(state_->mutex); - state_->current_thread = std::this_thread::get_id(); - // If paused we break out immediately. If finished we only break out - // when all work is done. - while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { - // The inner loop is to check if we need to sleep (e.g. while waiting on some - // async task to finish from another thread pool). We still need to check paused - // because sometimes we will pause even with work leftover when processing - // an async generator - while (!state_->paused && !state_->task_queue.empty()) { - Task task = std::move(state_->task_queue.front()); - state_->task_queue.pop_front(); - lk.unlock(); - if (!task.stop_token.IsStopRequested()) { - std::move(task.callable)(); - } else { - if (task.stop_callback) { - std::move(task.stop_callback)(task.stop_token.Poll()); - } - // Can't break here because there may be cleanup tasks down the chain we still - // need to run. - } - lk.lock(); - } - // In this case we must be waiting on work from external (e.g. I/O) executors. Wait - // for tasks to arrive (typically via transferred futures). - state_->wait_for_tasks.wait(lk, [&] { - return state_->paused || state_->finished || !state_->task_queue.empty(); - }); - } - state_->current_thread = {}; -} #endif //ARROW_ENABLE_THREADING -#ifndef ARROW_ENABLE_THREADING -ThreadPool::ThreadPool() -{ - // default to max 'concurrency' of 8 - // if threading is disabled - state_->max_tasks_running=8; -} -Status ThreadPool::Shutdown(bool wait) -{ - state_->finished=true; - if(wait) - { - RunLoop(); - }else - { - // clear any pending tasks so that we behave - // the same as threadpool on fast shutdown - state_->task_queue.clear(); - } - return Status::OK(); -} - -// Wait for the 'thread pool' to become idle -// including running tasks from other pools if -// needed -void ThreadPool::WaitForIdle() -{ - while(!state_->task_queue.empty()) - { - RunTasksOnAllExecutors(true); - } -} - -Result> ThreadPool::Make(int threads) { - auto pool = std::shared_ptr(new ThreadPool()); - RETURN_NOT_OK(pool->SetCapacity(threads)); - return pool; -} - -Result> ThreadPool::MakeEternal(int threads) { - ARROW_ASSIGN_OR_RAISE(auto pool, Make(threads)); - // On Windows, the ThreadPool destructor may be called after non-main threads - // have been killed by the OS, and hang in a condition variable. - // On Unix, we want to avoid leak reports by Valgrind. - return pool; -} -ThreadPool::~ThreadPool() -{ - // clear threadpool, otherwise ~SerialExecutor will - // run any tasks left (which isn't threadpool behaviour) - state_->task_queue.clear(); - -} - - -#else // ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING struct ThreadPool::State { State() = default; @@ -793,7 +720,78 @@ int ThreadPool::DefaultCapacity() { return capacity; } +#else // ARROW_ENABLE_THREADING +ThreadPool::ThreadPool() +{ + // default to max 'concurrency' of 8 + // if threading is disabled + state_->max_tasks_running=8; +} + +Status ThreadPool::Shutdown(bool wait) +{ + state_->finished=true; + if(wait) + { + RunLoop(); + }else + { + // clear any pending tasks so that we behave + // the same as threadpool on fast shutdown + state_->task_queue.clear(); + } + return Status::OK(); +} + +// Wait for the 'thread pool' to become idle +// including running tasks from other pools if +// needed +void ThreadPool::WaitForIdle() +{ + while(!state_->task_queue.empty()) + { + RunTasksOnAllExecutors(true); + } +} + +Status ThreadPool::SetCapacity(int threads) +{ + state_->max_tasks_running=threads; + return Status::OK(); +} + +int ThreadPool::GetCapacity() +{ + return state_->max_tasks_running; +} + +int ThreadPool::GetActualCapacity() +{ + return state_->max_tasks_running; +} + + +Result> ThreadPool::Make(int threads) { + auto pool = std::shared_ptr(new ThreadPool()); + RETURN_NOT_OK(pool->SetCapacity(threads)); + return pool; +} + +Result> ThreadPool::MakeEternal(int threads) { + ARROW_ASSIGN_OR_RAISE(auto pool, Make(threads)); + // On Windows, the ThreadPool destructor may be called after non-main threads + // have been killed by the OS, and hang in a condition variable. + // On Unix, we want to avoid leak reports by Valgrind. + return pool; +} +ThreadPool::~ThreadPool() +{ + // clear threadpool, otherwise ~SerialExecutor will + // run any tasks left (which isn't threadpool behaviour) + state_->task_queue.clear(); + +} #endif //ARROW_ENABLE_THREADING diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index e62703cb02bb..8e680eb47a3c 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -359,12 +359,12 @@ class ARROW_EXPORT SerialExecutor : public Executor { // the next call. executor->Pause(); }); -#ifndef ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING // future must run on this thread - next_fut.Wait(); -#else // Borrow this thread and run tasks until the future is finished executor->RunLoop(); +#else + next_fut.Wait(); #endif if (!next_fut.is_finished()) { // Not clear this is possible since RunLoop wouldn't generally exit @@ -393,7 +393,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { virtual bool IsCurrentExecutor() {return current_executor==this;} - #endif @@ -441,66 +440,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { }; -#ifndef ARROW_ENABLE_THREADING -// an executor implementation which pretends to be a thread pool but runs everything -// on the main thread using a static queue (shared between all thread pools, otherwise -// cross-threadpool dependencies will break everything) -class ARROW_EXPORT ThreadPool : public SerialExecutor -{ - public: - - ARROW_FRIEND_EXPORT friend ThreadPool* GetCpuThreadPool(); - - - static Result> Make(int threads); - - // Like Make(), but takes care that the returned ThreadPool is compatible - // with destruction late at process exit. - static Result> MakeEternal(int threads); - - // Destroy thread pool; the pool will first be shut down - ~ThreadPool() override; - - // Return the desired number of worker threads. - // The actual number of workers may lag a bit before being adjusted to - // match this value. - virtual int GetCapacity() override; - - virtual int GetActualCapacity(); - - bool OwnsThisThread() override - { - return true; - } - - // Dynamically change the number of worker threads. - // without threading this is equal to the - // number of tasks that can be running at once - // (inside each other) - Status SetCapacity(int threads); - - static int DefaultCapacity(){return 8;} - - // Shutdown the pool. Once the pool starts shutting down, new tasks - // cannot be submitted anymore. - // If "wait" is true, shutdown waits for all pending tasks to be finished. - // If "wait" is false, workers are stopped as soon as currently executing - // tasks are finished. - Status Shutdown(bool wait = true); - - // Wait for the thread pool to become idle - // - // This is useful for sequencing tests - void WaitForIdle(); - protected: - static std::shared_ptr MakeCpuThreadPool(); - ThreadPool(); - - - -}; - -#else // ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING /// An Executor implementation spawning tasks in FIFO manner on a fixed-size /// pool of worker threads. @@ -581,6 +521,65 @@ class ARROW_EXPORT ThreadPool : public Executor { State* state_; bool shutdown_on_destroy_; }; +#else // ARROW_ENABLE_THREADING +// an executor implementation which pretends to be a thread pool but runs everything +// on the main thread using a static queue (shared between all thread pools, otherwise +// cross-threadpool dependencies will break everything) +class ARROW_EXPORT ThreadPool : public SerialExecutor +{ + public: + + ARROW_FRIEND_EXPORT friend ThreadPool* GetCpuThreadPool(); + + + static Result> Make(int threads); + + // Like Make(), but takes care that the returned ThreadPool is compatible + // with destruction late at process exit. + static Result> MakeEternal(int threads); + + // Destroy thread pool; the pool will first be shut down + ~ThreadPool() override; + + // Return the desired number of worker threads. + // The actual number of workers may lag a bit before being adjusted to + // match this value. + virtual int GetCapacity() override; + + virtual int GetActualCapacity(); + + bool OwnsThisThread() override + { + return true; + } + + // Dynamically change the number of worker threads. + // without threading this is equal to the + // number of tasks that can be running at once + // (inside each other) + Status SetCapacity(int threads); + + static int DefaultCapacity(){return 8;} + + // Shutdown the pool. Once the pool starts shutting down, new tasks + // cannot be submitted anymore. + // If "wait" is true, shutdown waits for all pending tasks to be finished. + // If "wait" is false, workers are stopped as soon as currently executing + // tasks are finished. + Status Shutdown(bool wait = true); + + // Wait for the thread pool to become idle + // + // This is useful for sequencing tests + void WaitForIdle(); + protected: + static std::shared_ptr MakeCpuThreadPool(); + ThreadPool(); + + + +}; + #endif // ARROW_ENABLE_THREADING // Return the process-global thread pool for CPU-bound tasks. diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index 8fd89fcb3018..fae85c986d77 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -672,18 +672,7 @@ TEST_F(TestThreadPool, QuickShutdown) { add_tester.CheckNotAllComputed(); } -#ifndef ARROW_ENABLE_THREADING -TEST_F(TestThreadPool, SetCapacity) { - auto pool = this->MakeThreadPool(5); - - ASSERT_EQ(pool->GetCapacity(), 5); - ASSERT_EQ(pool->GetActualCapacity(), 5); - - ASSERT_OK(pool->SetCapacity(7)); - ASSERT_EQ(pool->GetCapacity(), 7); - -} -#else// ARROW_ENABLE_THREADING +#ifdef ARROW_ENABLE_THREADING TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); @@ -745,6 +734,17 @@ TEST_F(TestThreadPool, SetCapacity) { // Ensure nothing got stuck ASSERT_OK(pool->Shutdown()); } +#else // ARROW_ENABLE_THREADING +TEST_F(TestThreadPool, SetCapacity) { + auto pool = this->MakeThreadPool(5); + + ASSERT_EQ(pool->GetCapacity(), 5); + ASSERT_EQ(pool->GetActualCapacity(), 5); + + ASSERT_OK(pool->SetCapacity(7)); + ASSERT_EQ(pool->GetCapacity(), 7); + +} #endif // Test Submit() functionality From d644b961d896e303361758a7f4d3ddd8fa4ae3b6 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 12:54:34 +0100 Subject: [PATCH 48/79] lint fixes --- cpp/src/arrow/acero/asof_join_node.cc | 22 +-- cpp/src/arrow/acero/plan_test.cc | 2 +- cpp/src/arrow/acero/task_util.h | 2 +- cpp/src/arrow/acero/task_util_test.cc | 14 +- cpp/src/arrow/dataset/dataset_writer_test.cc | 24 +-- cpp/src/arrow/engine/substrait/serde_test.cc | 18 +- cpp/src/arrow/testing/gtest_util.cc | 155 ++++++++-------- cpp/src/arrow/util/async_generator_test.cc | 36 ++-- cpp/src/arrow/util/future.cc | 56 +++--- cpp/src/arrow/util/task_group.cc | 27 ++- cpp/src/arrow/util/thread_pool.cc | 186 +++++++------------ cpp/src/arrow/util/thread_pool.h | 129 ++++++------- cpp/src/arrow/util/thread_pool_test.cc | 61 +++--- 13 files changed, 334 insertions(+), 398 deletions(-) diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index f1b8916706b4..b528a3c0b46c 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -1514,18 +1514,18 @@ class AsofJoinNode : public ExecNode { } Status StartProducing() override { - #ifndef ARROW_ENABLE_THREADING - return Status::NotImplemented("ASOF join requires threading enabled"); - #endif - - ARROW_ASSIGN_OR_RAISE(process_task_, plan_->query_context()->BeginExternalTask( - "AsofJoinNode::ProcessThread")); - if (!process_task_.is_valid()) { - // Plan has already aborted. Do not start process thread - return Status::OK(); - } - process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); +#ifndef ARROW_ENABLE_THREADING + return Status::NotImplemented("ASOF join requires threading enabled"); +#endif + + ARROW_ASSIGN_OR_RAISE(process_task_, plan_->query_context()->BeginExternalTask( + "AsofJoinNode::ProcessThread")); + if (!process_task_.is_valid()) { + // Plan has already aborted. Do not start process thread return Status::OK(); + } + process_thread_ = std::thread(&AsofJoinNode::ProcessThreadWrapper, this); + return Status::OK(); } void PauseProducing(ExecNode* output, int32_t counter) override {} diff --git a/cpp/src/arrow/acero/plan_test.cc b/cpp/src/arrow/acero/plan_test.cc index d98c537158c3..55c673b5eb7d 100644 --- a/cpp/src/arrow/acero/plan_test.cc +++ b/cpp/src/arrow/acero/plan_test.cc @@ -1604,7 +1604,7 @@ TEST(ExecPlan, SourceEnforcesBatchLimit) { TEST(ExecPlanExecution, SegmentedAggregationWithMultiThreading) { #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading enabled"; -#endif +#endif BatchesWithSchema data; data.batches = {ExecBatchFromJSON({int32()}, "[[1]]")}; data.schema = schema({field("i32", int32())}); diff --git a/cpp/src/arrow/acero/task_util.h b/cpp/src/arrow/acero/task_util.h index 867b193b4655..fbd4af699d12 100644 --- a/cpp/src/arrow/acero/task_util.h +++ b/cpp/src/arrow/acero/task_util.h @@ -24,8 +24,8 @@ #include "arrow/acero/visibility.h" #include "arrow/status.h" -#include "arrow/util/logging.h" #include "arrow/util/config.h" +#include "arrow/util/logging.h" namespace arrow { namespace acero { diff --git a/cpp/src/arrow/acero/task_util_test.cc b/cpp/src/arrow/acero/task_util_test.cc index b209c85bb27d..06e6fd92f194 100644 --- a/cpp/src/arrow/acero/task_util_test.cc +++ b/cpp/src/arrow/acero/task_util_test.cc @@ -95,16 +95,15 @@ TaskScheduler::TaskGroupContinuationImpl MakeFinalContinuation( }; } - // This test simulates one of the current use patterns of the // task scheduler. There are a number of groups. The groups // are allocated to stages. All groups in a stage execute // concurrently. When all groups in that stage finish the next // stage is started. TEST(TaskScheduler, Stress) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif constexpr int kNumThreads = 8; constexpr int kNumGroups = 8; constexpr int kGroupsPerStage = 3; @@ -180,15 +179,14 @@ TEST(TaskScheduler, Stress) { // thread starts a task group while another thread is finishing // the last of its tasks. TEST(TaskScheduler, StressTwo) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif constexpr int kNumThreads = 16; constexpr int kNumGroups = 8; constexpr int kTasksPerGroup = 1; constexpr int kIterations = 1000; - ThreadIndexer thread_indexer; int num_threads = std::min(static_cast(thread_indexer.Capacity()), kNumThreads); ASSERT_OK_AND_ASSIGN(std::shared_ptr thread_pool, diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index 8358a097acf1..3fbee7de9f55 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -380,11 +380,11 @@ TEST_F(DatasetWriterTestFixture, MinRowGroupBackpressure) { } TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { - // Use a gated filesystem to queue up many writes behind a file open to make sure the - // file isn't opened multiple times. - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Concurrent writes tests need threads"; - #endif +// Use a gated filesystem to queue up many writes behind a file open to make sure the +// file isn't opened multiple times. +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; +#endif auto gated_fs = UseGatedFs(); auto dataset_writer = MakeDatasetWriter(); for (int i = 0; i < 10; i++) { @@ -397,10 +397,10 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { } TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { - // NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Concurrent writes tests need threads"; - #endif +// NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; +#endif constexpr int NBATCHES = 6; auto gated_fs = UseGatedFs(); std::vector expected_files; @@ -418,9 +418,9 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { } TEST_F(DatasetWriterTestFixture, MaxOpenFiles) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Concurrent writes tests need threads"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Concurrent writes tests need threads"; +#endif auto gated_fs = UseGatedFs(); std::atomic paused = false; write_options_.max_open_files = 2; diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc b/cpp/src/arrow/engine/substrait/serde_test.cc index 10d0bc9b058f..6f838db962a0 100644 --- a/cpp/src/arrow/engine/substrait/serde_test.cc +++ b/cpp/src/arrow/engine/substrait/serde_test.cc @@ -4458,9 +4458,9 @@ TEST(Substrait, SetRelationBasic) { } TEST(Substrait, PlanWithAsOfJoinExtension) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "ASOF join requires threading"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; +#endif // This demos an extension relation std::string substrait_json = R"({ "extensionUris": [], @@ -5480,9 +5480,9 @@ TEST(Substrait, MixedSort) { } TEST(Substrait, PlanWithExtension) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "ASOF join requires threading"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; +#endif // This demos an extension relation std::string substrait_json = R"({ @@ -5672,9 +5672,9 @@ TEST(Substrait, PlanWithExtension) { } TEST(Substrait, AsOfJoinDefaultEmit) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "ASOF join requires threading"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "ASOF join requires threading"; +#endif std::string substrait_json = R"({ "extensionUris": [], "extensions": [], diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 7e1af70e5532..23168c6a6f4c 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -729,21 +729,19 @@ void SleepFor(double seconds) { std::this_thread::sleep_for( std::chrono::nanoseconds(static_cast(seconds * 1e9))); #else - std::chrono::duration secs_left=std::chrono::duration(seconds); - auto start_time = std::chrono::steady_clock::now(); - auto end_time= start_time+secs_left; - auto now=start_time; - while(now < end_time) - { - bool run_task=arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); - now= std::chrono::steady_clock::now(); - if(!run_task) - { - // all executors are empty, just sleep for the rest of the time - std::this_thread::sleep_for(end_time-now); - } - // run one task then check time - } + std::chrono::duration secs_left = std::chrono::duration(seconds); + auto start_time = std::chrono::steady_clock::now(); + auto end_time = start_time + secs_left; + auto now = start_time; + while (now < end_time) { + bool run_task = arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + now = std::chrono::steady_clock::now(); + if (!run_task) { + // all executors are empty, just sleep for the rest of the time + std::this_thread::sleep_for(end_time - now); + } + // run one task then check time + } #endif } @@ -1054,26 +1052,25 @@ class GatingTask::Impl : public std::enable_shared_from_this { return unlocked_future_; } - void _WaitForEndOrUnlocked(std::chrono::time_point end_time,arrow::internal::Executor *executor,Future<> future) - { - if(unlocked_) - { + void _WaitForEndOrUnlocked(std::chrono::time_point end_time, + arrow::internal::Executor* executor, Future<> future) { + if (unlocked_) { num_finished_++; future.MarkFinished(Status::OK()); - return; - }else - { - if(std::chrono::steady_clock::now()>end_time) - { + return; + } else { + if (std::chrono::steady_clock::now() > end_time) { num_finished_++; - future.MarkFinished(Status::Invalid("Task unlock never happened - if threads are disabled you can't wait on gatedtask")); + future.MarkFinished( + Status::Invalid("Task unlock never happened - if threads are disabled you " + "can't wait on gatedtask")); return; - }else - { + } else { SleepABit(); - auto spawn_status=executor->Spawn([this,end_time,executor,future](){_WaitForEndOrUnlocked(end_time,executor,future);}); - if(!spawn_status.ok()) - { + auto spawn_status = executor->Spawn([this, end_time, executor, future]() { + _WaitForEndOrUnlocked(end_time, executor, future); + }); + if (!spawn_status.ok()) { status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); } } @@ -1081,49 +1078,52 @@ class GatingTask::Impl : public std::enable_shared_from_this { } Future<> RunTaskFuture() { - num_running_++; - // post the unlock check as a separate task - // otherwise we'll never let anything else run - // so nothing can unlock us - using Clock=std::chrono::steady_clock; - using DurationDouble=std::chrono::duration; - using DurationClock=std::chrono::steady_clock::duration; - - auto start_time = Clock::now(); - std::chrono::duration secs_left=std::chrono::duration(timeout_seconds_); - std::chrono::time_point end_time=std::chrono::time_point_cast(start_time+secs_left); - arrow::internal::Executor *executor=arrow::internal::GetCpuThreadPool(); - Future<> future=Future<>::Make(); - auto spawn_status=executor->Spawn([this,end_time,executor,future](){_WaitForEndOrUnlocked(end_time,executor,future);}); - if(!spawn_status.ok()) - { - status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); - future.MarkFinished(Status::Invalid("")); - } - return future; + num_running_++; + // post the unlock check as a separate task + // otherwise we'll never let anything else run + // so nothing can unlock us + using Clock = std::chrono::steady_clock; + using DurationDouble = std::chrono::duration; + using DurationClock = std::chrono::steady_clock::duration; + + auto start_time = Clock::now(); + std::chrono::duration secs_left = + std::chrono::duration(timeout_seconds_); + std::chrono::time_point end_time = + std::chrono::time_point_cast(start_time + + secs_left); + arrow::internal::Executor* executor = arrow::internal::GetCpuThreadPool(); + Future<> future = Future<>::Make(); + auto spawn_status = executor->Spawn([this, end_time, executor, future]() { + _WaitForEndOrUnlocked(end_time, executor, future); + }); + if (!spawn_status.ok()) { + status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); + future.MarkFinished(Status::Invalid("")); + } + return future; } - void RunTask() { - #ifdef ARROW_ENABLE_THREADING - std::unique_lock lk(mx_); - num_running_++; - running_cv_.notify_all(); - if (!unlocked_cv_.wait_for( - lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), - [this] { return unlocked_; })) { - status_ &= Status::Invalid("Timed out (" + std::to_string(timeout_seconds_) + "," + - std::to_string(unlocked_) + - " seconds) waiting for the gating task to be unlocked"); - } - num_finished_++; - #else +#ifdef ARROW_ENABLE_THREADING + std::unique_lock lk(mx_); + num_running_++; + running_cv_.notify_all(); + if (!unlocked_cv_.wait_for( + lk, std::chrono::nanoseconds(static_cast(timeout_seconds_ * 1e9)), + [this] { return unlocked_; })) { + status_ &= Status::Invalid("Timed out (" + std::to_string(timeout_seconds_) + "," + + std::to_string(unlocked_) + + " seconds) waiting for the gating task to be unlocked"); + } + num_finished_++; +#else // can't wait here for anything, so make a future to do the waiting - num_running_++; - auto future=RunTaskFuture(); - future.Wait(); - return; - #endif + num_running_++; + auto future = RunTaskFuture(); + future.Wait(); + return; +#endif } Status WaitForRunning(int count) { @@ -1135,16 +1135,14 @@ class GatingTask::Impl : public std::enable_shared_from_this { return Status::OK(); } return Status::Invalid("Timed out waiting for tasks to launch"); -#else - BusyWait(timeout_seconds_,[this, count] { return num_running_ >= count; }); - if(num_running_>=count) - { - return Status::OK(); - }else - { +#else + BusyWait(timeout_seconds_, [this, count] { return num_running_ >= count; }); + if (num_running_ >= count) { + return Status::OK(); + } else { return Status::Invalid("Timed out waiting for tasks to launch"); } -#endif +#endif } Status Unlock() { @@ -1155,8 +1153,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { } unlocked_future_.MarkFinished(); #ifndef ARROW_ENABLE_THREADING - while(num_finished_!=num_running_) - { + while (num_finished_ != num_running_) { arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); } #endif diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 97dbe2c0fbdf..9ce818cbd576 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -994,9 +994,9 @@ TEST(TestAsyncUtil, GeneratorIterator) { } TEST(TestAsyncUtil, MakeTransferredGenerator) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif std::mutex mutex; std::condition_variable cv; std::atomic finished(false); @@ -1498,14 +1498,15 @@ TEST(TestAsyncUtil, ReadaheadFailed) { return TestInt(count); })); #else - // if threading is disabled, we can't call Task() as we do below because it will - // never return and will block everything + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything if (count == 0) { - return gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); - }else{ - return gating_task->AsyncTask().Then([count](){return TestInt(count);}); + return gating_task->AsyncTask().Then( + []() { return Future::MakeFinished(Status::Invalid("X")); }); + } else { + return gating_task->AsyncTask().Then([count]() { return TestInt(count); }); } -#endif +#endif }; auto readahead = MakeReadaheadGenerator(source, 10); auto should_be_invalid = readahead(); @@ -1536,7 +1537,7 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { auto count = counter++; #ifdef ARROW_ENABLE_THREADING - return DeferNotOk(thread_pool->Submit([&, count]() -> Result { + return DeferNotOk(thread_pool->Submit([&, count]() -> Result { if (count == 0) { failure_gating_task->Task()(); return Status::Invalid("X"); @@ -1546,15 +1547,16 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { return TestInt(0); })); #else - // if threading is disabled, we can't call Task() as we do below because it will - // never return and will block everything + // if threading is disabled, we can't call Task() as we do below because it will + // never return and will block everything if (count == 0) { - return failure_gating_task->AsyncTask().Then([](){return Future::MakeFinished(Status::Invalid("X"));}); - }else{ - return in_flight_gating_task->AsyncTask().Then([](){return TestInt(0);}); + return failure_gating_task->AsyncTask().Then( + []() { return Future::MakeFinished(Status::Invalid("X")); }); + } else { + return in_flight_gating_task->AsyncTask().Then([]() { return TestInt(0); }); } - #endif - }; +#endif + }; auto readahead = MakeReadaheadGenerator(source, 10); auto should_be_invalid = readahead(); ASSERT_OK(in_flight_gating_task->WaitForRunning(10)); diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index d1ee497c4f2f..14b57a774199 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -149,42 +149,38 @@ class ConcreteFutureImpl : public FutureImpl { } void DoWait() { - #ifdef ARROW_ENABLE_THREADING - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { return IsFutureFinished(state_); }); - #else - while(true) - { - if(IsFutureFinished(state_)) - { - return; - } - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); +#ifdef ARROW_ENABLE_THREADING + std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { return IsFutureFinished(state_); }); +#else + while (true) { + if (IsFutureFinished(state_)) { + return; } - #endif + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } +#endif } bool DoWait(double seconds) { - #ifdef ARROW_ENABLE_THREADING - std::unique_lock lock(mutex_); +#ifdef ARROW_ENABLE_THREADING + std::unique_lock lock(mutex_); - cv_.wait_for(lock, std::chrono::duration(seconds), - [this] { return IsFutureFinished(state_); }); - return IsFutureFinished(state_); - #else - auto start = std::chrono::steady_clock::now(); - std::chrono::duration fsec=std::chrono::duration(seconds); - while(std::chrono::steady_clock::now()-start < fsec) - { - // run one task then check time - if(IsFutureFinished(state_)) - { - return true; - } - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + cv_.wait_for(lock, std::chrono::duration(seconds), + [this] { return IsFutureFinished(state_); }); + return IsFutureFinished(state_); +#else + auto start = std::chrono::steady_clock::now(); + std::chrono::duration fsec = std::chrono::duration(seconds); + while (std::chrono::steady_clock::now() - start < fsec) { + // run one task then check time + if (IsFutureFinished(state_)) { + return true; } - return IsFutureFinished(state_); - #endif + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } + return IsFutureFinished(state_); +#endif } std::mutex mutex_; diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index c36cad32ffb3..b2f49500974e 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -128,22 +128,21 @@ class ThreadedTaskGroup : public TaskGroup { bool ok() const override { return ok_.load(); } Status Finish() override { - #ifdef ARROW_ENABLE_THREADING - std::unique_lock lock(mutex_); - if (!finished_) { - cv_.wait(lock, [&]() { return nremaining_.load() == 0; }); - // Current tasks may start other tasks, so only set this when done - finished_ = true; - } - #else - while(!finished_ && nremaining_.load() != 0 ) - { - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); - } +#ifdef ARROW_ENABLE_THREADING + std::unique_lock lock(mutex_); + if (!finished_) { + cv_.wait(lock, [&]() { return nremaining_.load() == 0; }); + // Current tasks may start other tasks, so only set this when done finished_ = true; - #endif - return status_; } +#else + while (!finished_ && nremaining_.load() != 0) { + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + } + finished_ = true; +#endif + return status_; + } Future<> FinishAsync() override { std::lock_guard lock(mutex_); diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index fda868bf7bbd..1ac8db1bed9e 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -45,7 +45,6 @@ void Executor::KeepAlive(std::shared_ptr resource) {} namespace { - struct Task { FnOnce callable; StopToken stop_token; @@ -64,26 +63,23 @@ struct SerialExecutor::State { #ifndef ARROW_ENABLE_THREADING int max_tasks_running{1}; int tasks_running{0}; -#endif +#endif }; #ifndef ARROW_ENABLE_THREADING -// list of all SerialExecutor objects - as we need to run tasks from all pools at once in Run() +// list of all SerialExecutor objects - as we need to run tasks from all pools at once in +// Run() std::unordered_set SerialExecutor::all_executors; -SerialExecutor* SerialExecutor::current_executor=NULL; -SerialExecutor* SerialExecutor::GetCurrentExecutor() -{ - return current_executor; -} -SerialExecutor* SerialExecutor::last_called_executor=NULL; +SerialExecutor* SerialExecutor::current_executor = NULL; +SerialExecutor* SerialExecutor::GetCurrentExecutor() { return current_executor; } +SerialExecutor* SerialExecutor::last_called_executor = NULL; #endif -SerialExecutor::SerialExecutor() : state_(std::make_shared()) -{ +SerialExecutor::SerialExecutor() : state_(std::make_shared()) { #ifndef ARROW_ENABLE_THREADING all_executors.insert(this); - state_->max_tasks_running=1; + state_->max_tasks_running = 1; #endif } @@ -103,8 +99,7 @@ SerialExecutor::~SerialExecutor() { } } -int SerialExecutor::GetNumTasks() -{ +int SerialExecutor::GetNumTasks() { auto state = state_; return (int)(state_->task_queue.size()); } @@ -153,7 +148,7 @@ void SerialExecutor::Finish() { state->wait_for_tasks.notify_one(); } -#else // ARROW_ENABLE_THREADING +#else // ARROW_ENABLE_THREADING Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, StopToken stop_token, StopCallback&& stop_callback) { #ifdef ARROW_WITH_OPENTELEMETRY @@ -165,7 +160,7 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, auto scope = ::arrow::internal::tracing::GetTracer()->WithActiveSpan(active_span); std::move(func)(); }; -#endif// ARROW_WITH_OPENTELEMETRY +#endif // ARROW_WITH_OPENTELEMETRY if (state_->finished) { return Status::Invalid( @@ -173,21 +168,20 @@ Status SerialExecutor::SpawnReal(TaskHints hints, FnOnce task, "been abandoned"); } - state_->task_queue.push_back( Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); + state_->task_queue.push_back( + Task{std::move(task), std::move(stop_token), std::move(stop_callback)}); - return Status::OK(); + return Status::OK(); } void SerialExecutor::Finish() { auto state = state_; - { - state->finished = true; - } + { state->finished = true; } // empty any tasks from the loop on finish RunLoop(); } -#endif // ARROW_ENABLE_THREADING +#endif // ARROW_ENABLE_THREADING void SerialExecutor::Pause() { // Same comment as SpawnReal above auto state = state_; @@ -198,7 +192,6 @@ void SerialExecutor::Pause() { state->wait_for_tasks.notify_one(); } - bool SerialExecutor::IsFinished() { std::lock_guard lk(state_->mutex); return state_->finished; @@ -218,8 +211,6 @@ bool SerialExecutor::OwnsThisThread() { } #ifdef ARROW_ENABLE_THREADING - - void SerialExecutor::RunLoop() { // This is called from the SerialExecutor's main thread, so the // state is guaranteed to be kept alive. @@ -255,31 +246,26 @@ void SerialExecutor::RunLoop() { } state_->current_thread = {}; } -#else // ARROW_ENABLE_THREADING -bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) -{ - if(last_called_executor!=NULL && all_executors.count(last_called_executor)==0) - { - last_called_executor=NULL; - } - bool run_task=true; - bool keep_going=true; - while(keep_going) - { - run_task=false; - keep_going=false; - for(auto it=all_executors.begin();it!=all_executors.end();++it) - { - if(last_called_executor!=NULL) - { - // always rerun loop if we have a last_called_executor, otherwise +#else // ARROW_ENABLE_THREADING +bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { + if (last_called_executor != NULL && all_executors.count(last_called_executor) == 0) { + last_called_executor = NULL; + } + bool run_task = true; + bool keep_going = true; + while (keep_going) { + run_task = false; + keep_going = false; + for (auto it = all_executors.begin(); it != all_executors.end(); ++it) { + if (last_called_executor != NULL) { + // always rerun loop if we have a last_called_executor, otherwise // we drop out before everything is - keep_going=true; - if(all_executors.count(last_called_executor)==0 || last_called_executor==*it) - { + keep_going = true; + if (all_executors.count(last_called_executor) == 0 || + last_called_executor == *it) { // found the last one (or it doesn't exist ih the set any more) // now we can start running things - last_called_executor=NULL; + last_called_executor = NULL; } // skip until after we have seen the last executor we called // so that we do things nicely in turn @@ -288,18 +274,16 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) SerialExecutor* exe = *it; // don't make reentrant calls inside a serialexecutor // or more than the number of concurrent tasks set on a threadpool - if(exe->state_->tasks_running >= exe->state_->max_tasks_running) - { + if (exe->state_->tasks_running >= exe->state_->max_tasks_running) { continue; } - if(exe->state_->paused==false && exe->state_->task_queue.empty()==false) - { - SerialExecutor* old_exe=current_executor; - current_executor=exe; + if (exe->state_->paused == false && exe->state_->task_queue.empty() == false) { + SerialExecutor* old_exe = current_executor; + current_executor = exe; Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); - run_task=true; - exe->state_->tasks_running+=1; + run_task = true; + exe->state_->tasks_running += 1; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); } else { @@ -307,17 +291,15 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) std::move(task.stop_callback)(task.stop_token.Poll()); } } - exe->state_->tasks_running-=1; - current_executor=old_exe; + exe->state_->tasks_running -= 1; + current_executor = old_exe; - if(once_only) - { - last_called_executor=exe; - keep_going=false; + if (once_only) { + last_called_executor = exe; + keep_going = false; break; - }else - { - keep_going=true; + } else { + keep_going = true; } } } @@ -327,23 +309,20 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) // run tasks in this thread and queue things from other executors if required // (e.g. when a compute task depends on an IO request) -void SerialExecutor::RunLoop() -{ +void SerialExecutor::RunLoop() { // If paused we break out immediately. If finished we only break out // when all work is done. while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { // first empty us until paused or empty // if we're already running as many tasks as possible then // we can't run any more until something else drops off the queue - if(state_->tasks_running <= state_->max_tasks_running) - { - + if (state_->tasks_running <= state_->max_tasks_running) { while (!state_->paused && !state_->task_queue.empty()) { Task task = std::move(state_->task_queue.front()); state_->task_queue.pop_front(); - auto last_executor=current_executor; - current_executor=this; - state_->tasks_running+=1; + auto last_executor = current_executor; + current_executor = this; + state_->tasks_running += 1; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); } else { @@ -351,24 +330,19 @@ void SerialExecutor::RunLoop() std::move(task.stop_callback)(task.stop_token.Poll()); } } - state_->tasks_running-=1; - current_executor=last_executor; + state_->tasks_running -= 1; + current_executor = last_executor; } - if(state_->paused || (state_->finished && state_->task_queue.empty())) - { + if (state_->paused || (state_->finished && state_->task_queue.empty())) { break; } } - // now wait for anything on other executors (unless we're finished in which case it will drop out of - // the outer loop + // now wait for anything on other executors (unless we're finished in which case it + // will drop out of the outer loop RunTasksOnAllExecutors(true); } - } -#endif //ARROW_ENABLE_THREADING - - - +#endif // ARROW_ENABLE_THREADING #ifdef ARROW_ENABLE_THREADING @@ -720,22 +694,18 @@ int ThreadPool::DefaultCapacity() { return capacity; } -#else // ARROW_ENABLE_THREADING -ThreadPool::ThreadPool() -{ +#else // ARROW_ENABLE_THREADING +ThreadPool::ThreadPool() { // default to max 'concurrency' of 8 // if threading is disabled - state_->max_tasks_running=8; + state_->max_tasks_running = 8; } -Status ThreadPool::Shutdown(bool wait) -{ - state_->finished=true; - if(wait) - { +Status ThreadPool::Shutdown(bool wait) { + state_->finished = true; + if (wait) { RunLoop(); - }else - { + } else { // clear any pending tasks so that we behave // the same as threadpool on fast shutdown state_->task_queue.clear(); @@ -746,30 +716,20 @@ Status ThreadPool::Shutdown(bool wait) // Wait for the 'thread pool' to become idle // including running tasks from other pools if // needed -void ThreadPool::WaitForIdle() -{ - while(!state_->task_queue.empty()) - { +void ThreadPool::WaitForIdle() { + while (!state_->task_queue.empty()) { RunTasksOnAllExecutors(true); } } -Status ThreadPool::SetCapacity(int threads) -{ - state_->max_tasks_running=threads; +Status ThreadPool::SetCapacity(int threads) { + state_->max_tasks_running = threads; return Status::OK(); } -int ThreadPool::GetCapacity() -{ - return state_->max_tasks_running; -} - -int ThreadPool::GetActualCapacity() -{ - return state_->max_tasks_running; -} +int ThreadPool::GetCapacity() { return state_->max_tasks_running; } +int ThreadPool::GetActualCapacity() { return state_->max_tasks_running; } Result> ThreadPool::Make(int threads) { auto pool = std::shared_ptr(new ThreadPool()); @@ -785,15 +745,13 @@ Result> ThreadPool::MakeEternal(int threads) { return pool; } -ThreadPool::~ThreadPool() -{ +ThreadPool::~ThreadPool() { // clear threadpool, otherwise ~SerialExecutor will // run any tasks left (which isn't threadpool behaviour) state_->task_queue.clear(); - } -#endif //ARROW_ENABLE_THREADING +#endif // ARROW_ENABLE_THREADING // Helper for the singleton pattern std::shared_ptr ThreadPool::MakeCpuThreadPool() { diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 8e680eb47a3c..79875b8b3345 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -21,13 +21,13 @@ #include #include #include -#include #include +#include -#include "arrow/util/config.h" #include "arrow/result.h" #include "arrow/status.h" #include "arrow/util/cancel.h" +#include "arrow/util/config.h" #include "arrow/util/functional.h" #include "arrow/util/future.h" #include "arrow/util/iterator.h" @@ -198,9 +198,8 @@ class ARROW_EXPORT Executor { // Return true if this is the current executor being called // n.b. this defaults to just calling OwnsThisThread - // unless the threadpool is disabled - virtual bool IsCurrentExecutor() {return OwnsThisThread();} - + // unless the threadpool is disabled + virtual bool IsCurrentExecutor() { return OwnsThisThread(); } /// \brief An interface to represent something with a custom destructor /// @@ -279,7 +278,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { ~SerialExecutor() override; - virtual int GetCapacity() override { return 1; }; + int GetCapacity() override { return 1; }; bool OwnsThisThread() override; Status SpawnReal(TaskHints hints, FnOnce task, StopToken, StopCallback&&) override; @@ -287,7 +286,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { // Return the number of tasks either running or in the queue. int GetNumTasks(); - /// \brief Runs the TopLevelTask and any scheduled tasks /// /// The TopLevelTask (or one of the tasks it schedules) must either return an invalid @@ -385,18 +383,17 @@ class ARROW_EXPORT SerialExecutor : public Executor { } #ifndef ARROW_ENABLE_THREADING - // run loop until everything is done (or one go round loop if once_only=True) - // returns true if any tasks were run in the last go round the loop (i.e. if it - // returns false, all executors are waiting) - static bool RunTasksOnAllExecutors(bool once_only=false); - static SerialExecutor* GetCurrentExecutor(); + // run loop until everything is done (or one go round loop if once_only=True) + // returns true if any tasks were run in the last go round the loop (i.e. if it + // returns false, all executors are waiting) + static bool RunTasksOnAllExecutors(bool once_only = false); + static SerialExecutor* GetCurrentExecutor(); - virtual bool IsCurrentExecutor() {return current_executor==this;} + virtual bool IsCurrentExecutor() { return current_executor == this; } #endif - -protected: + protected: virtual void RunLoop(); // State uses mutex @@ -405,7 +402,6 @@ class ARROW_EXPORT SerialExecutor : public Executor { SerialExecutor(); - // We mark the serial executor "finished" when there should be // no more tasks scheduled on it. It's not strictly needed but // can help catch bugs where we are trying to use the executor @@ -423,21 +419,20 @@ class ARROW_EXPORT SerialExecutor : public Executor { final_fut.AddCallback([this](const FTSync&) { Finish(); }); RunLoop(); return final_fut; - } + } #ifndef ARROW_ENABLE_THREADING // we have to run tasks from all live executors // during RunLoop if we don't have threading - static std::unordered_set all_executors; - // a pointer to the last one called by the loop - // so all tasks get spawned equally - // on multiple calls to RunTasksOnAllExecutors - static SerialExecutor* last_called_executor; - // without threading we can't tell which executor called the - // current process - so we set it in spawning the task - static SerialExecutor* current_executor; -#endif // ARROW_ENABLE_THREADING - + static std::unordered_set all_executors; + // a pointer to the last one called by the loop + // so all tasks get spawned equally + // on multiple calls to RunTasksOnAllExecutors + static SerialExecutor* last_called_executor; + // without threading we can't tell which executor called the + // current process - so we set it in spawning the task + static SerialExecutor* current_executor; +#endif // ARROW_ENABLE_THREADING }; #ifdef ARROW_ENABLE_THREADING @@ -521,66 +516,58 @@ class ARROW_EXPORT ThreadPool : public Executor { State* state_; bool shutdown_on_destroy_; }; -#else // ARROW_ENABLE_THREADING +#else // ARROW_ENABLE_THREADING // an executor implementation which pretends to be a thread pool but runs everything // on the main thread using a static queue (shared between all thread pools, otherwise // cross-threadpool dependencies will break everything) -class ARROW_EXPORT ThreadPool : public SerialExecutor -{ - public: - - ARROW_FRIEND_EXPORT friend ThreadPool* GetCpuThreadPool(); - - - static Result> Make(int threads); +class ARROW_EXPORT ThreadPool : public SerialExecutor { + public: + ARROW_FRIEND_EXPORT friend ThreadPool* GetCpuThreadPool(); - // Like Make(), but takes care that the returned ThreadPool is compatible - // with destruction late at process exit. - static Result> MakeEternal(int threads); + static Result> Make(int threads); - // Destroy thread pool; the pool will first be shut down - ~ThreadPool() override; + // Like Make(), but takes care that the returned ThreadPool is compatible + // with destruction late at process exit. + static Result> MakeEternal(int threads); - // Return the desired number of worker threads. - // The actual number of workers may lag a bit before being adjusted to - // match this value. - virtual int GetCapacity() override; + // Destroy thread pool; the pool will first be shut down + ~ThreadPool() override; - virtual int GetActualCapacity(); - - bool OwnsThisThread() override - { - return true; - } + // Return the desired number of worker threads. + // The actual number of workers may lag a bit before being adjusted to + // match this value. + int GetCapacity() override; - // Dynamically change the number of worker threads. - // without threading this is equal to the - // number of tasks that can be running at once - // (inside each other) - Status SetCapacity(int threads); + virtual int GetActualCapacity(); - static int DefaultCapacity(){return 8;} + bool OwnsThisThread() override { return true; } - // Shutdown the pool. Once the pool starts shutting down, new tasks - // cannot be submitted anymore. - // If "wait" is true, shutdown waits for all pending tasks to be finished. - // If "wait" is false, workers are stopped as soon as currently executing - // tasks are finished. - Status Shutdown(bool wait = true); + // Dynamically change the number of worker threads. + // without threading this is equal to the + // number of tasks that can be running at once + // (inside each other) + Status SetCapacity(int threads); - // Wait for the thread pool to become idle - // - // This is useful for sequencing tests - void WaitForIdle(); - protected: - static std::shared_ptr MakeCpuThreadPool(); - ThreadPool(); + static int DefaultCapacity() { return 8; } + // Shutdown the pool. Once the pool starts shutting down, new tasks + // cannot be submitted anymore. + // If "wait" is true, shutdown waits for all pending tasks to be finished. + // If "wait" is false, workers are stopped as soon as currently executing + // tasks are finished. + Status Shutdown(bool wait = true); + // Wait for the thread pool to become idle + // + // This is useful for sequencing tests + void WaitForIdle(); + protected: + static std::shared_ptr MakeCpuThreadPool(); + ThreadPool(); }; -#endif // ARROW_ENABLE_THREADING +#endif // ARROW_ENABLE_THREADING // Return the process-global thread pool for CPU-bound tasks. ARROW_EXPORT ThreadPool* GetCpuThreadPool(); diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index fae85c986d77..225dbfda28a4 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -341,7 +341,7 @@ TEST(SerialExecutor, AsyncGeneratorWithCleanup) { // must run before the terminal item is delivered from the iterator. bool follow_up_ran = false; Iterator iter = - + SerialExecutor::IterateGenerator([&](Executor* executor) { return [=, &follow_up_ran]() -> Future { Future end = @@ -584,9 +584,9 @@ TEST_F(TestThreadPool, StressSpawn) { } TEST_F(TestThreadPool, OwnsCurrentThread) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif auto pool = this->MakeThreadPool(30); std::atomic one_failed{false}; @@ -603,9 +603,9 @@ TEST_F(TestThreadPool, OwnsCurrentThread) { ASSERT_FALSE(one_failed); } TEST_F(TestThreadPool, StressSpawnThreaded) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_add); @@ -623,9 +623,9 @@ TEST_F(TestThreadPool, StressSpawnSlow) { } TEST_F(TestThreadPool, StressSpawnSlowThreaded) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_slow_add{/*seconds=*/0.002}); } @@ -637,9 +637,9 @@ TEST_F(TestThreadPool, SpawnWithStopToken) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopToken) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif StopSource stop_source; auto pool = this->MakeThreadPool(30); SpawnAddsThreaded(pool.get(), 20, 100, task_add, stop_source.token()); @@ -652,9 +652,9 @@ TEST_F(TestThreadPool, SpawnWithStopTokenCancelled) { } TEST_F(TestThreadPool, StressSpawnThreadedWithStopTokenCancelled) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif StopSource stop_source; auto pool = this->MakeThreadPool(30); SpawnAddsThreadedAndCancel(pool.get(), 20, 100, task_slow_add{/*seconds=*/0.02}, @@ -734,7 +734,7 @@ TEST_F(TestThreadPool, SetCapacity) { // Ensure nothing got stuck ASSERT_OK(pool->Shutdown()); } -#else // ARROW_ENABLE_THREADING +#else // ARROW_ENABLE_THREADING TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(5); @@ -743,7 +743,6 @@ TEST_F(TestThreadPool, SetCapacity) { ASSERT_OK(pool->SetCapacity(7)); ASSERT_EQ(pool->GetCapacity(), 7); - } #endif // Test Submit() functionality @@ -830,10 +829,10 @@ class TestThreadPoolForkSafety : public TestThreadPool {}; TEST_F(TestThreadPoolForkSafety, Basics) { { - #ifndef ARROW_ENABLE_THREADING +#ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; - #endif - +#endif + // Fork after task submission auto pool = this->MakeThreadPool(3); ASSERT_OK_AND_ASSIGN(auto fut, pool->Submit(add, 4, 5)); @@ -877,12 +876,12 @@ TEST_F(TestThreadPoolForkSafety, Basics) { } TEST_F(TestThreadPoolForkSafety, MultipleChildThreads) { - // ARROW-15593: race condition in after-fork ThreadPool reinitialization - // when SpawnReal() was called from multiple threads in a forked child. - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif - auto run_in_child = [](ThreadPool* pool) { +// ARROW-15593: race condition in after-fork ThreadPool reinitialization +// when SpawnReal() was called from multiple threads in a forked child. +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif + auto run_in_child = [](ThreadPool* pool) { const int n_threads = 5; std::vector> futures; std::vector threads; @@ -931,7 +930,7 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { GTEST_SKIP() << "Nested fork is not supported on macos"; #endif #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; + GTEST_SKIP() << "Test requires threading support"; #endif auto pool = this->MakeThreadPool(3); ASSERT_OK_AND_ASSIGN(auto fut, pool->Submit(add, 4, 5)); @@ -966,9 +965,9 @@ TEST_F(TestThreadPoolForkSafety, NestedChild) { #endif TEST(TestGlobalThreadPool, Capacity) { - #ifndef ARROW_ENABLE_THREADING - GTEST_SKIP() << "Test requires threading support"; - #endif +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif // Sanity check auto pool = GetCpuThreadPool(); int capacity = pool->GetCapacity(); From d81947841c4d54cdeb73609332ba09493b0276cf Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 13:12:57 +0100 Subject: [PATCH 49/79] made sure everything that uses ENABLE_THREADING includes util/config.h --- cpp/src/arrow/acero/asof_join_node.cc | 1 + cpp/src/arrow/acero/bloom_filter.cc | 1 + cpp/src/arrow/acero/bloom_filter_test.cc | 1 + cpp/src/arrow/acero/plan_test.cc | 1 + cpp/src/arrow/acero/task_util.cc | 1 + cpp/src/arrow/acero/task_util_test.cc | 1 + cpp/src/arrow/dataset/dataset_writer_test.cc | 2 ++ cpp/src/arrow/engine/substrait/serde_test.cc | 1 + cpp/src/arrow/io/memory_test.cc | 1 + cpp/src/arrow/testing/gtest_util.cc | 1 + cpp/src/arrow/util/async_generator_test.cc | 1 + cpp/src/arrow/util/future.cc | 1 + cpp/src/arrow/util/mutex.h | 2 +- cpp/src/arrow/util/task_group.cc | 1 + cpp/src/arrow/util/thread_pool.cc | 1 + cpp/src/arrow/util/thread_pool_test.cc | 1 + 16 files changed, 17 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/acero/asof_join_node.cc b/cpp/src/arrow/acero/asof_join_node.cc index b528a3c0b46c..65558f570d68 100644 --- a/cpp/src/arrow/acero/asof_join_node.cc +++ b/cpp/src/arrow/acero/asof_join_node.cc @@ -42,6 +42,7 @@ #include "arrow/type_traits.h" #include "arrow/util/bit_util.h" #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/future.h" #include "arrow/util/string.h" diff --git a/cpp/src/arrow/acero/bloom_filter.cc b/cpp/src/arrow/acero/bloom_filter.cc index b3aeda9c2da6..af24c1e28dd6 100644 --- a/cpp/src/arrow/acero/bloom_filter.cc +++ b/cpp/src/arrow/acero/bloom_filter.cc @@ -20,6 +20,7 @@ #include "arrow/acero/util.h" // PREFETCH #include "arrow/util/bit_util.h" // Log2 #include "arrow/util/bitmap_ops.h" // CountSetBits +#include "arrow/util/config.h" namespace arrow { namespace acero { diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index dd1644580e1c..2226b68a2301 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -28,6 +28,7 @@ #include "arrow/acero/util.h" #include "arrow/compute/key_hash.h" #include "arrow/util/bitmap_ops.h" +#include "arrow/util/config.h" #include "arrow/util/cpu_info.h" namespace arrow { diff --git a/cpp/src/arrow/acero/plan_test.cc b/cpp/src/arrow/acero/plan_test.cc index 55c673b5eb7d..1e91782218ed 100644 --- a/cpp/src/arrow/acero/plan_test.cc +++ b/cpp/src/arrow/acero/plan_test.cc @@ -36,6 +36,7 @@ #include "arrow/testing/matchers.h" #include "arrow/testing/random.h" #include "arrow/util/async_generator.h" +#include "arrow/util/config.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" #include "arrow/util/thread_pool.h" diff --git a/cpp/src/arrow/acero/task_util.cc b/cpp/src/arrow/acero/task_util.cc index c68b100a8076..4d8e9ecf7659 100644 --- a/cpp/src/arrow/acero/task_util.cc +++ b/cpp/src/arrow/acero/task_util.cc @@ -20,6 +20,7 @@ #include #include +#include "arrow/util/config.h" #include "arrow/util/logging.h" namespace arrow { diff --git a/cpp/src/arrow/acero/task_util_test.cc b/cpp/src/arrow/acero/task_util_test.cc index 06e6fd92f194..d5196ad4e0a0 100644 --- a/cpp/src/arrow/acero/task_util_test.cc +++ b/cpp/src/arrow/acero/task_util_test.cc @@ -27,6 +27,7 @@ #include "arrow/acero/util.h" #include "arrow/testing/gtest_util.h" +#include "arrow/util/config.h" #include "arrow/util/thread_pool.h" namespace arrow { diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index 3fbee7de9f55..feb06188b21d 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -20,6 +20,7 @@ #include #include #include + #include #include "arrow/array/builder_primitive.h" @@ -28,6 +29,7 @@ #include "arrow/filesystem/test_util.h" #include "arrow/io/memory.h" #include "arrow/ipc/reader.h" +#include "arrow/util/config.h" #include "arrow/table.h" #include "arrow/testing/future_util.h" #include "arrow/testing/gtest_util.h" diff --git a/cpp/src/arrow/engine/substrait/serde_test.cc b/cpp/src/arrow/engine/substrait/serde_test.cc index 6f838db962a0..efe1f702b486 100644 --- a/cpp/src/arrow/engine/substrait/serde_test.cc +++ b/cpp/src/arrow/engine/substrait/serde_test.cc @@ -71,6 +71,7 @@ #include "arrow/type_fwd.h" #include "arrow/util/async_generator_fwd.h" #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/decimal.h" #include "arrow/util/future.h" #include "arrow/util/hash_util.h" diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index 683aa80e99ab..99bb01974996 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -41,6 +41,7 @@ #include "arrow/testing/gtest_util.h" #include "arrow/testing/util.h" #include "arrow/util/bit_util.h" +#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" #include "arrow/util/future.h" #include "arrow/util/iterator.h" diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 23168c6a6f4c..bf54308c80c6 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -54,6 +54,7 @@ #include "arrow/status.h" #include "arrow/table.h" #include "arrow/type.h" +#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" #include "arrow/util/future.h" #include "arrow/util/io_util.h" diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 9ce818cbd576..8e7c8d1e373b 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -32,6 +32,7 @@ #include "arrow/type_fwd.h" #include "arrow/util/async_generator.h" #include "arrow/util/async_util.h" +#include "arrow/util/config.h" #include "arrow/util/test_common.h" #include "arrow/util/vector.h" diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 14b57a774199..90bc5a3af849 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -25,6 +25,7 @@ #include #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/logging.h" #include "arrow/util/thread_pool.h" #include "arrow/util/tracing_internal.h" diff --git a/cpp/src/arrow/util/mutex.h b/cpp/src/arrow/util/mutex.h index ac63cf70cd9a..606bc0c7290e 100644 --- a/cpp/src/arrow/util/mutex.h +++ b/cpp/src/arrow/util/mutex.h @@ -32,7 +32,7 @@ class ARROW_EXPORT Mutex { public: Mutex(); Mutex(Mutex&&) = default; - Mutex& operator=(Mutex&&) = default; + Mutex& operator=(Mutex&&) = default;l` /// A Guard is falsy if a lock could not be acquired. class ARROW_EXPORT Guard { diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index b2f49500974e..711e3d7ec214 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -23,6 +23,7 @@ #include #include +#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" #include "arrow/util/logging.h" #include "arrow/util/thread_pool.h" diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 1ac8db1bed9e..4faf6b07d3d0 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -27,6 +27,7 @@ #include #include "arrow/util/atfork_internal.h" +#include "arrow/util/config.h" #include "arrow/util/io_util.h" #include "arrow/util/logging.h" #include "arrow/util/mutex.h" diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index 225dbfda28a4..2023a0613fe7 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -37,6 +37,7 @@ #include "arrow/testing/executor_util.h" #include "arrow/testing/future_util.h" #include "arrow/testing/gtest_util.h" +#include "arrow/util/config.h" #include "arrow/util/io_util.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" From f17eb67412d7357f74bf00dca6cf32abc9adf0a6 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 13:21:46 +0100 Subject: [PATCH 50/79] cat typing --- cpp/src/arrow/util/mutex.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/mutex.h b/cpp/src/arrow/util/mutex.h index 606bc0c7290e..ac63cf70cd9a 100644 --- a/cpp/src/arrow/util/mutex.h +++ b/cpp/src/arrow/util/mutex.h @@ -32,7 +32,7 @@ class ARROW_EXPORT Mutex { public: Mutex(); Mutex(Mutex&&) = default; - Mutex& operator=(Mutex&&) = default;l` + Mutex& operator=(Mutex&&) = default; /// A Guard is falsy if a lock could not be acquired. class ARROW_EXPORT Guard { From 4cba8745c9fc9c669a4bdc1c393a96fb7465f0a4 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 24 May 2023 13:51:59 +0100 Subject: [PATCH 51/79] restored ThirdpartyToolchain correctly --- cpp/cmake_modules/ThirdpartyToolchain.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake index a67b87e5a3e1..a764acb6ce0f 100644 --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -2325,7 +2325,7 @@ macro(build_benchmark) endmacro() if(ARROW_BUILD_BENCHMARKS) - set(BENCHMARK_REQUIRED_VERSION 1.6.0) + set(BENCHMARK_REQUIRED_VERSION 1.6.1) resolve_dependency(benchmark REQUIRED_VERSION ${BENCHMARK_REQUIRED_VERSION} From b8ceb23f3395b85ffeac7cd176a2f03cdb20a81c Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Thu, 25 May 2023 09:53:00 +0100 Subject: [PATCH 52/79] removed blankspace lint change --- cpp/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 83409657d4e7..c81427058c9a 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -370,7 +370,6 @@ if(ARROW_ENABLE_TIMING_TESTS) add_definitions(-DARROW_WITH_TIMING_TESTS) endif() - if(NOT ARROW_BUILD_BENCHMARKS) set(NO_BENCHMARKS 1) else() @@ -920,6 +919,7 @@ endif() # Handle platform-related libraries like -pthread set(ARROW_SYSTEM_LINK_LIBS) + list(APPEND ARROW_SYSTEM_LINK_LIBS Threads::Threads) if(CMAKE_THREAD_LIBS_INIT) string(APPEND ARROW_PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") From d2b9a30d5969855f2bfa8c2601569135d1a5e875 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Thu, 25 May 2023 09:59:32 +0100 Subject: [PATCH 53/79] reverted whitespace changes --- cpp/src/arrow/acero/CMakeLists.txt | 1 - cpp/src/arrow/dataset/dataset_writer_test.cc | 1 - 2 files changed, 2 deletions(-) diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index b1281c7d864c..be33acb4ad87 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -55,7 +55,6 @@ set(ARROW_ACERO_SRCS union_node.cc util.cc) - append_acero_avx2_src(bloom_filter_avx2.cc) append_acero_avx2_src(swiss_join_avx2.cc) diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index feb06188b21d..bd4dc31bdade 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -20,7 +20,6 @@ #include #include #include - #include #include "arrow/array/builder_primitive.h" From c93b788504d5319ad7ae7301061d8cb0f641a990 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Thu, 25 May 2023 13:40:50 +0100 Subject: [PATCH 54/79] fixed alphabetical order of includes --- cpp/src/arrow/dataset/dataset_writer_test.cc | 2 +- cpp/src/arrow/io/memory_test.cc | 2 +- cpp/src/arrow/testing/gtest_util.cc | 2 +- cpp/src/arrow/util/task_group.cc | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index bd4dc31bdade..de9cd8a7fd57 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -28,10 +28,10 @@ #include "arrow/filesystem/test_util.h" #include "arrow/io/memory.h" #include "arrow/ipc/reader.h" -#include "arrow/util/config.h" #include "arrow/table.h" #include "arrow/testing/future_util.h" #include "arrow/testing/gtest_util.h" +#include "arrow/util/config.h" #include "gtest/gtest.h" using namespace std::string_view_literals; // NOLINT diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index 99bb01974996..a83a305fb7eb 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -41,8 +41,8 @@ #include "arrow/testing/gtest_util.h" #include "arrow/testing/util.h" #include "arrow/util/bit_util.h" -#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/future.h" #include "arrow/util/iterator.h" #include "arrow/util/logging.h" diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index bf54308c80c6..21a4ded77981 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -54,8 +54,8 @@ #include "arrow/status.h" #include "arrow/table.h" #include "arrow/type.h" -#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/future.h" #include "arrow/util/io_util.h" #include "arrow/util/logging.h" diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 711e3d7ec214..5ac911d04da1 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -23,8 +23,8 @@ #include #include -#include "arrow/util/config.h" #include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" #include "arrow/util/logging.h" #include "arrow/util/thread_pool.h" From bd96259ff9544e5c010faf9709ab4335dcf94b96 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 31 May 2023 11:15:58 +0100 Subject: [PATCH 55/79] cmake lint fixes --- cpp/cmake_modules/DefineOptions.cmake | 4 +--- cpp/src/arrow/acero/CMakeLists.txt | 10 +++++----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/cpp/cmake_modules/DefineOptions.cmake b/cpp/cmake_modules/DefineOptions.cmake index 066844119535..015c7f713165 100644 --- a/cpp/cmake_modules/DefineOptions.cmake +++ b/cpp/cmake_modules/DefineOptions.cmake @@ -210,9 +210,7 @@ takes precedence over ccache if a storage backend is configured" ON) define_option(ARROW_WITH_MUSL "Whether the system libc is musl or not" OFF) - define_option(ARROW_ENABLE_THREADING "Enable threading in Arrow core." - ON) - + define_option(ARROW_ENABLE_THREADING "Enable threading in Arrow core." ON) #---------------------------------------------------------------------- set_option_category("Test and benchmark") diff --git a/cpp/src/arrow/acero/CMakeLists.txt b/cpp/src/arrow/acero/CMakeLists.txt index be33acb4ad87..5a73a8ae80ef 100644 --- a/cpp/src/arrow/acero/CMakeLists.txt +++ b/cpp/src/arrow/acero/CMakeLists.txt @@ -220,9 +220,9 @@ if(ARROW_BUILD_BENCHMARKS) add_arrow_acero_benchmark(project_benchmark SOURCES benchmark_util.cc project_benchmark.cc) -if(ARROW_ENABLE_THREADING) - add_arrow_acero_benchmark(asof_join_benchmark SOURCES asof_join_benchmark.cc) -endif() + if(ARROW_ENABLE_THREADING) + add_arrow_acero_benchmark(asof_join_benchmark SOURCES asof_join_benchmark.cc) + endif() add_arrow_acero_benchmark(tpch_benchmark SOURCES tpch_benchmark.cc) @@ -245,7 +245,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_static) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_static) - if(ARROW_ENABLE_THREADING) + if(ARROW_ENABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_static) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_static) @@ -256,7 +256,7 @@ endif() target_link_libraries(arrow-acero-expression-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-filter-benchmark PUBLIC arrow_acero_shared) target_link_libraries(arrow-acero-project-benchmark PUBLIC arrow_acero_shared) - if(ARROW_ENABLE_THREADING) + if(ARROW_ENABLE_THREADING) target_link_libraries(arrow-acero-asof-join-benchmark PUBLIC arrow_acero_shared) endif() target_link_libraries(arrow-acero-tpch-benchmark PUBLIC arrow_acero_shared) From 4c4f43b6c6b455eaec9f96e3f359d0fce29aed91 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 2 Jun 2023 09:50:13 +0100 Subject: [PATCH 56/79] Update cpp/cmake_modules/DefineOptions.cmake Co-authored-by: Sutou Kouhei --- cpp/cmake_modules/DefineOptions.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/cmake_modules/DefineOptions.cmake b/cpp/cmake_modules/DefineOptions.cmake index 015c7f713165..4243d2ad3fdf 100644 --- a/cpp/cmake_modules/DefineOptions.cmake +++ b/cpp/cmake_modules/DefineOptions.cmake @@ -210,7 +210,7 @@ takes precedence over ccache if a storage backend is configured" ON) define_option(ARROW_WITH_MUSL "Whether the system libc is musl or not" OFF) - define_option(ARROW_ENABLE_THREADING "Enable threading in Arrow core." ON) + define_option(ARROW_ENABLE_THREADING "Enable threading in Arrow core" ON) #---------------------------------------------------------------------- set_option_category("Test and benchmark") From 8f9305fb8e67afb304595f06a364797884b67e37 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 2 Jun 2023 09:50:46 +0100 Subject: [PATCH 57/79] Update cpp/src/arrow/dataset/dataset_writer_test.cc Co-authored-by: Sutou Kouhei --- cpp/src/arrow/dataset/dataset_writer_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index de9cd8a7fd57..ced27648f195 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -398,10 +398,10 @@ TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { } TEST_F(DatasetWriterTestFixture, ConcurrentWritesDifferentFiles) { -// NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; #endif + // NBATCHES must be less than I/O executor concurrency to avoid deadlock / test failure constexpr int NBATCHES = 6; auto gated_fs = UseGatedFs(); std::vector expected_files; From 8e101be1e3884a5e2e661de2074eb8814345485a Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 2 Jun 2023 13:10:39 +0100 Subject: [PATCH 58/79] review fixes --- cpp/src/arrow/io/memory_test.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index a83a305fb7eb..7ac16bf1cc51 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -870,8 +870,10 @@ TEST(CacheOptions, Basics) { check(CacheOptions::MakeFromNetworkMetrics(5, 500, .75, 5), 2.5, 5); } -#ifdef ARROW_ENABLE_THREADING TEST(IOThreadPool, Capacity) { +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading enabled"; +#endif // Simple sanity check auto pool = internal::GetIOThreadPool(); int capacity = pool->GetCapacity(); @@ -880,7 +882,6 @@ TEST(IOThreadPool, Capacity) { ASSERT_OK(SetIOThreadPoolCapacity(capacity + 1)); ASSERT_EQ(GetIOThreadPoolCapacity(), capacity + 1); } -#endif } // namespace io } // namespace arrow From c64497f1f19ad132d6e3573995e49d1cdea620d6 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 2 Jun 2023 13:11:29 +0100 Subject: [PATCH 59/79] comment ordering (from review) Co-authored-by: Sutou Kouhei --- cpp/src/arrow/dataset/dataset_writer_test.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index ced27648f195..c76e79d79b44 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -381,11 +381,11 @@ TEST_F(DatasetWriterTestFixture, MinRowGroupBackpressure) { } TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { -// Use a gated filesystem to queue up many writes behind a file open to make sure the -// file isn't opened multiple times. #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; #endif + // Use a gated filesystem to queue up many writes behind a file open to make sure the + // file isn't opened multiple times. auto gated_fs = UseGatedFs(); auto dataset_writer = MakeDatasetWriter(); for (int i = 0; i < 10; i++) { From 162bde04d234601df041dedf6ebc69ca05d26190 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 6 Jun 2023 21:01:04 +0100 Subject: [PATCH 60/79] lint fixes --- cpp/src/arrow/io/memory_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/io/memory_test.cc b/cpp/src/arrow/io/memory_test.cc index 7ac16bf1cc51..93c16668f247 100644 --- a/cpp/src/arrow/io/memory_test.cc +++ b/cpp/src/arrow/io/memory_test.cc @@ -873,7 +873,7 @@ TEST(CacheOptions, Basics) { TEST(IOThreadPool, Capacity) { #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading enabled"; -#endif +#endif // Simple sanity check auto pool = internal::GetIOThreadPool(); int capacity = pool->GetCapacity(); From 90bdfd6f0bee2f6409d66624a132e26d4675a755 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 6 Jun 2023 21:01:49 +0100 Subject: [PATCH 61/79] Update cpp/src/arrow/testing/gtest_util.cc Co-authored-by: Sutou Kouhei --- cpp/src/arrow/testing/gtest_util.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 9f823baa111c..8d89eff5ad06 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -730,7 +730,7 @@ void SleepFor(double seconds) { std::this_thread::sleep_for( std::chrono::nanoseconds(static_cast(seconds * 1e9))); #else - std::chrono::duration secs_left = std::chrono::duration(seconds); + auto secs_left = std::chrono::duration(seconds); auto start_time = std::chrono::steady_clock::now(); auto end_time = start_time + secs_left; auto now = start_time; From 94ce7bc9940cbf8c4ce0e2c97ca606beed2ac866 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Tue, 6 Jun 2023 21:02:25 +0100 Subject: [PATCH 62/79] Update cpp/src/arrow/testing/gtest_util.cc Co-authored-by: Sutou Kouhei --- cpp/src/arrow/testing/gtest_util.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 8d89eff5ad06..6e47b4293aee 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -733,8 +733,7 @@ void SleepFor(double seconds) { auto secs_left = std::chrono::duration(seconds); auto start_time = std::chrono::steady_clock::now(); auto end_time = start_time + secs_left; - auto now = start_time; - while (now < end_time) { + while (std::chrono::steady_clock::now() < end_time) { bool run_task = arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); now = std::chrono::steady_clock::now(); if (!run_task) { From c1420e02be2f3dba197cc0e3e3cfdc1d9e4e1966 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 7 Jun 2023 07:00:42 +0100 Subject: [PATCH 63/79] review fixes --- cpp/src/arrow/util/future.cc | 1 + cpp/src/arrow/util/thread_pool_test.cc | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 90bc5a3af849..5d9e3d72eade 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -152,6 +152,7 @@ class ConcreteFutureImpl : public FutureImpl { void DoWait() { #ifdef ARROW_ENABLE_THREADING std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { return IsFutureFinished(state_); }); #else while (true) { diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index 2023a0613fe7..c95d634cc749 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -877,11 +877,11 @@ TEST_F(TestThreadPoolForkSafety, Basics) { } TEST_F(TestThreadPoolForkSafety, MultipleChildThreads) { -// ARROW-15593: race condition in after-fork ThreadPool reinitialization -// when SpawnReal() was called from multiple threads in a forked child. #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif +// ARROW-15593: race condition in after-fork ThreadPool reinitialization +// when SpawnReal() was called from multiple threads in a forked child. auto run_in_child = [](ThreadPool* pool) { const int n_threads = 5; std::vector> futures; From 5dab2ea641a2e3234a555b95e5fca2645b1dde8a Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 7 Jun 2023 12:22:26 +0100 Subject: [PATCH 64/79] review updates --- cpp/src/arrow/testing/gtest_util.cc | 3 +-- cpp/src/arrow/util/thread_pool_test.cc | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 9f823baa111c..e0d14dbe122e 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -739,7 +739,7 @@ void SleepFor(double seconds) { now = std::chrono::steady_clock::now(); if (!run_task) { // all executors are empty, just sleep for the rest of the time - std::this_thread::sleep_for(end_time - now); + std::this_thread::sleep_for(end_time - std::chrono::steady_clock::now()); } // run one task then check time } @@ -1123,7 +1123,6 @@ class GatingTask::Impl : public std::enable_shared_from_this { num_running_++; auto future = RunTaskFuture(); future.Wait(); - return; #endif } diff --git a/cpp/src/arrow/util/thread_pool_test.cc b/cpp/src/arrow/util/thread_pool_test.cc index c95d634cc749..ad30ca2e8052 100644 --- a/cpp/src/arrow/util/thread_pool_test.cc +++ b/cpp/src/arrow/util/thread_pool_test.cc @@ -342,7 +342,6 @@ TEST(SerialExecutor, AsyncGeneratorWithCleanup) { // must run before the terminal item is delivered from the iterator. bool follow_up_ran = false; Iterator iter = - SerialExecutor::IterateGenerator([&](Executor* executor) { return [=, &follow_up_ran]() -> Future { Future end = @@ -603,6 +602,7 @@ TEST_F(TestThreadPool, OwnsCurrentThread) { ASSERT_FALSE(pool->OwnsThisThread()); ASSERT_FALSE(one_failed); } + TEST_F(TestThreadPool, StressSpawnThreaded) { #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; @@ -880,8 +880,8 @@ TEST_F(TestThreadPoolForkSafety, MultipleChildThreads) { #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Test requires threading support"; #endif -// ARROW-15593: race condition in after-fork ThreadPool reinitialization -// when SpawnReal() was called from multiple threads in a forked child. + // ARROW-15593: race condition in after-fork ThreadPool reinitialization + // when SpawnReal() was called from multiple threads in a forked child. auto run_in_child = [](ThreadPool* pool) { const int n_threads = 5; std::vector> futures; From a5a14bbd8b8e19bb7192a0fc6992029dc304a6e3 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Thu, 8 Jun 2023 10:05:08 +0100 Subject: [PATCH 65/79] lint --- cpp/src/arrow/util/future.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 5d9e3d72eade..bb4d55197ad2 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -152,7 +152,7 @@ class ConcreteFutureImpl : public FutureImpl { void DoWait() { #ifdef ARROW_ENABLE_THREADING std::unique_lock lock(mutex_); - + cv_.wait(lock, [this] { return IsFutureFinished(state_); }); #else while (true) { From 5224e4d5ebfcc425480eb19e8eeedfe026e7caac Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 23 Jun 2023 11:57:46 +0100 Subject: [PATCH 66/79] review fixes Co-authored-by: Weston Pace --- cpp/src/arrow/util/thread_pool.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 4faf6b07d3d0..07768e6f7b35 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -102,7 +102,7 @@ SerialExecutor::~SerialExecutor() { int SerialExecutor::GetNumTasks() { auto state = state_; - return (int)(state_->task_queue.size()); + return static_cast(state_->task_queue.size()); } #ifdef ARROW_ENABLE_THREADING From 5fb29c73766e747817c486c038c99272e75ab20f Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 23 Jun 2023 13:04:54 +0100 Subject: [PATCH 67/79] moved global state into thread_pool.cc --- cpp/src/arrow/util/thread_pool.cc | 65 +++++++++++++++++++++---------- cpp/src/arrow/util/thread_pool.h | 2 +- 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 07768e6f7b35..a7c2607223f3 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -70,23 +70,43 @@ struct SerialExecutor::State { #ifndef ARROW_ENABLE_THREADING // list of all SerialExecutor objects - as we need to run tasks from all pools at once in // Run() -std::unordered_set SerialExecutor::all_executors; -SerialExecutor* SerialExecutor::current_executor = NULL; -SerialExecutor* SerialExecutor::GetCurrentExecutor() { return current_executor; } -SerialExecutor* SerialExecutor::last_called_executor = NULL; +struct SerialExecutorGlobalState { + // a set containing all the executors that currently exist + std::unordered_set all_executors; + + // this is the executor which is currently running a task + SerialExecutor* current_executor = NULL; + + // in RunTasksOnAllExecutors we run tasks on executors in turn + // this is used to keep track of the last fired task so that it + // doesn't always run tasks on the first executor + // in case of nested calls to RunTasksOnAllExecutors + SerialExecutor* last_called_executor = NULL; +}; + +static SerialExecutorGlobalState& GetSerialExecutorGlobalState() { + static SerialExecutorGlobalState state; + return state; +} + +SerialExecutor* SerialExecutor::GetCurrentExecutor() { + return GetSerialExecutorGlobalState().current_executor; +} + +bool SerialExecutor::IsCurrentExecutor() { return GetCurrentExecutor() == this; } #endif SerialExecutor::SerialExecutor() : state_(std::make_shared()) { #ifndef ARROW_ENABLE_THREADING - all_executors.insert(this); + GetSerialExecutorGlobalState().all_executors.insert(this); state_->max_tasks_running = 1; #endif } SerialExecutor::~SerialExecutor() { #ifndef ARROW_ENABLE_THREADING - all_executors.erase(this); + GetSerialExecutorGlobalState().all_executors.erase(this); #endif auto state = state_; std::unique_lock lk(state->mutex); @@ -249,24 +269,28 @@ void SerialExecutor::RunLoop() { } #else // ARROW_ENABLE_THREADING bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { - if (last_called_executor != NULL && all_executors.count(last_called_executor) == 0) { - last_called_executor = NULL; + auto globalState = GetSerialExecutorGlobalState(); + // if the previously called executor was deleted, ignore last_called_executor + if (globalState.last_called_executor != NULL && + globalState.all_executors.count(globalState.last_called_executor) == 0) { + globalState.last_called_executor = NULL; } bool run_task = true; bool keep_going = true; while (keep_going) { run_task = false; keep_going = false; - for (auto it = all_executors.begin(); it != all_executors.end(); ++it) { - if (last_called_executor != NULL) { + for (auto it = globalState.all_executors.begin(); + it != globalState.all_executors.end(); ++it) { + if (globalState.last_called_executor != NULL) { // always rerun loop if we have a last_called_executor, otherwise // we drop out before everything is keep_going = true; - if (all_executors.count(last_called_executor) == 0 || - last_called_executor == *it) { + if (globalState.all_executors.count(globalState.last_called_executor) == 0 || + globalState.last_called_executor == *it) { // found the last one (or it doesn't exist ih the set any more) // now we can start running things - last_called_executor = NULL; + globalState.last_called_executor = NULL; } // skip until after we have seen the last executor we called // so that we do things nicely in turn @@ -279,8 +303,8 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { continue; } if (exe->state_->paused == false && exe->state_->task_queue.empty() == false) { - SerialExecutor* old_exe = current_executor; - current_executor = exe; + SerialExecutor* old_exe = globalState.current_executor; + globalState.current_executor = exe; Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); run_task = true; @@ -293,10 +317,10 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { } } exe->state_->tasks_running -= 1; - current_executor = old_exe; + globalState.current_executor = old_exe; if (once_only) { - last_called_executor = exe; + globalState.last_called_executor = exe; keep_going = false; break; } else { @@ -311,6 +335,7 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { // run tasks in this thread and queue things from other executors if required // (e.g. when a compute task depends on an IO request) void SerialExecutor::RunLoop() { + auto globalState = GetSerialExecutorGlobalState(); // If paused we break out immediately. If finished we only break out // when all work is done. while (!state_->paused && !(state_->finished && state_->task_queue.empty())) { @@ -321,8 +346,8 @@ void SerialExecutor::RunLoop() { while (!state_->paused && !state_->task_queue.empty()) { Task task = std::move(state_->task_queue.front()); state_->task_queue.pop_front(); - auto last_executor = current_executor; - current_executor = this; + auto last_executor = globalState.current_executor; + globalState.current_executor = this; state_->tasks_running += 1; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); @@ -332,7 +357,7 @@ void SerialExecutor::RunLoop() { } } state_->tasks_running -= 1; - current_executor = last_executor; + globalState.current_executor = last_executor; } if (state_->paused || (state_->finished && state_->task_queue.empty())) { break; diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 79875b8b3345..57aeb044ae37 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -389,7 +389,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { static bool RunTasksOnAllExecutors(bool once_only = false); static SerialExecutor* GetCurrentExecutor(); - virtual bool IsCurrentExecutor() { return current_executor == this; } + virtual bool IsCurrentExecutor(); #endif From 4e737994b2d84d9eed17d5e0f5e2b6f3863f64b2 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 23 Jun 2023 15:00:58 +0100 Subject: [PATCH 68/79] typo in gtest_util removed --- cpp/src/arrow/testing/gtest_util.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 01f3d2f3e3a5..0353720d044f 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -735,7 +735,6 @@ void SleepFor(double seconds) { auto end_time = start_time + secs_left; while (std::chrono::steady_clock::now() < end_time) { bool run_task = arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); - now = std::chrono::steady_clock::now(); if (!run_task) { // all executors are empty, just sleep for the rest of the time std::this_thread::sleep_for(end_time - std::chrono::steady_clock::now()); From 18ebc4e89a2743f6fdbbfd5f6b414818fde4f7ab Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 26 Jun 2023 15:44:13 +0100 Subject: [PATCH 69/79] updated threadpool to use static local for global state --- cpp/src/arrow/util/thread_pool.cc | 42 +++++++++++++++---------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index a7c2607223f3..96fcb4279e93 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -84,13 +84,13 @@ struct SerialExecutorGlobalState { SerialExecutor* last_called_executor = NULL; }; -static SerialExecutorGlobalState& GetSerialExecutorGlobalState() { +static SerialExecutorGlobalState* GetSerialExecutorGlobalState() { static SerialExecutorGlobalState state; - return state; + return &state; } SerialExecutor* SerialExecutor::GetCurrentExecutor() { - return GetSerialExecutorGlobalState().current_executor; + return GetSerialExecutorGlobalState()->current_executor; } bool SerialExecutor::IsCurrentExecutor() { return GetCurrentExecutor() == this; } @@ -99,14 +99,14 @@ bool SerialExecutor::IsCurrentExecutor() { return GetCurrentExecutor() == this; SerialExecutor::SerialExecutor() : state_(std::make_shared()) { #ifndef ARROW_ENABLE_THREADING - GetSerialExecutorGlobalState().all_executors.insert(this); + GetSerialExecutorGlobalState()->all_executors.insert(this); state_->max_tasks_running = 1; #endif } SerialExecutor::~SerialExecutor() { #ifndef ARROW_ENABLE_THREADING - GetSerialExecutorGlobalState().all_executors.erase(this); + GetSerialExecutorGlobalState()->all_executors.erase(this); #endif auto state = state_; std::unique_lock lk(state->mutex); @@ -271,26 +271,26 @@ void SerialExecutor::RunLoop() { bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { auto globalState = GetSerialExecutorGlobalState(); // if the previously called executor was deleted, ignore last_called_executor - if (globalState.last_called_executor != NULL && - globalState.all_executors.count(globalState.last_called_executor) == 0) { - globalState.last_called_executor = NULL; + if (globalState->last_called_executor != NULL && + globalState->all_executors.count(globalState->last_called_executor) == 0) { + globalState->last_called_executor = NULL; } bool run_task = true; bool keep_going = true; while (keep_going) { run_task = false; keep_going = false; - for (auto it = globalState.all_executors.begin(); - it != globalState.all_executors.end(); ++it) { - if (globalState.last_called_executor != NULL) { + for (auto it = globalState->all_executors.begin(); + it != globalState->all_executors.end(); ++it) { + if (globalState->last_called_executor != NULL) { // always rerun loop if we have a last_called_executor, otherwise // we drop out before everything is keep_going = true; - if (globalState.all_executors.count(globalState.last_called_executor) == 0 || - globalState.last_called_executor == *it) { + if (globalState->all_executors.count(globalState->last_called_executor) == 0 || + globalState->last_called_executor == *it) { // found the last one (or it doesn't exist ih the set any more) // now we can start running things - globalState.last_called_executor = NULL; + globalState->last_called_executor = NULL; } // skip until after we have seen the last executor we called // so that we do things nicely in turn @@ -303,8 +303,8 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { continue; } if (exe->state_->paused == false && exe->state_->task_queue.empty() == false) { - SerialExecutor* old_exe = globalState.current_executor; - globalState.current_executor = exe; + SerialExecutor* old_exe = globalState->current_executor; + globalState->current_executor = exe; Task task = std::move(exe->state_->task_queue.front()); exe->state_->task_queue.pop_front(); run_task = true; @@ -317,10 +317,10 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { } } exe->state_->tasks_running -= 1; - globalState.current_executor = old_exe; + globalState->current_executor = old_exe; if (once_only) { - globalState.last_called_executor = exe; + globalState->last_called_executor = exe; keep_going = false; break; } else { @@ -346,8 +346,8 @@ void SerialExecutor::RunLoop() { while (!state_->paused && !state_->task_queue.empty()) { Task task = std::move(state_->task_queue.front()); state_->task_queue.pop_front(); - auto last_executor = globalState.current_executor; - globalState.current_executor = this; + auto last_executor = globalState->current_executor; + globalState->current_executor = this; state_->tasks_running += 1; if (!task.stop_token.IsStopRequested()) { std::move(task.callable)(); @@ -357,7 +357,7 @@ void SerialExecutor::RunLoop() { } } state_->tasks_running -= 1; - globalState.current_executor = last_executor; + globalState->current_executor = last_executor; } if (state_->paused || (state_->finished && state_->task_queue.empty())) { break; From d9e997cd319719cd63993c538e0717b254cf9da0 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Mon, 26 Jun 2023 15:52:51 +0100 Subject: [PATCH 70/79] removed leading underscore on method --- cpp/src/arrow/testing/gtest_util.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 0353720d044f..f8842a04d39a 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -1051,7 +1051,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { return unlocked_future_; } - void _WaitForEndOrUnlocked(std::chrono::time_point end_time, + void WaitForEndOrUnlocked(std::chrono::time_point end_time, arrow::internal::Executor* executor, Future<> future) { if (unlocked_) { num_finished_++; @@ -1067,7 +1067,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { } else { SleepABit(); auto spawn_status = executor->Spawn([this, end_time, executor, future]() { - _WaitForEndOrUnlocked(end_time, executor, future); + WaitForEndOrUnlocked(end_time, executor, future); }); if (!spawn_status.ok()) { status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); @@ -1094,7 +1094,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { arrow::internal::Executor* executor = arrow::internal::GetCpuThreadPool(); Future<> future = Future<>::Make(); auto spawn_status = executor->Spawn([this, end_time, executor, future]() { - _WaitForEndOrUnlocked(end_time, executor, future); + WaitForEndOrUnlocked(end_time, executor, future); }); if (!spawn_status.ok()) { status_ &= Status::Invalid("Couldn't spawn gating task unlock waiter"); From 798b7cb115d09486ed3f7d5b876e07485f0fbb35 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 30 Jun 2023 13:18:59 +0100 Subject: [PATCH 71/79] lint --- cpp/src/arrow/testing/gtest_util.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index f8842a04d39a..3d919258a861 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -1052,7 +1052,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { } void WaitForEndOrUnlocked(std::chrono::time_point end_time, - arrow::internal::Executor* executor, Future<> future) { + arrow::internal::Executor* executor, Future<> future) { if (unlocked_) { num_finished_++; future.MarkFinished(Status::OK()); From 85c4e7e241bc25df8e56775e78be2374fb2b49e1 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Thu, 13 Jul 2023 14:21:36 +0100 Subject: [PATCH 72/79] fixes for review: --- cpp/src/arrow/testing/gtest_util.cc | 4 ++-- cpp/src/arrow/util/future.cc | 4 ++-- cpp/src/arrow/util/task_group.cc | 2 +- cpp/src/arrow/util/thread_pool.cc | 14 +++++++++----- cpp/src/arrow/util/thread_pool.h | 4 ++-- 5 files changed, 16 insertions(+), 12 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 3d919258a861..71c052e84e3b 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -734,7 +734,7 @@ void SleepFor(double seconds) { auto start_time = std::chrono::steady_clock::now(); auto end_time = start_time + secs_left; while (std::chrono::steady_clock::now() < end_time) { - bool run_task = arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + bool run_task = arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); if (!run_task) { // all executors are empty, just sleep for the rest of the time std::this_thread::sleep_for(end_time - std::chrono::steady_clock::now()); @@ -1152,7 +1152,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { unlocked_future_.MarkFinished(); #ifndef ARROW_ENABLE_THREADING while (num_finished_ != num_running_) { - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); } #endif diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index bb4d55197ad2..a3cf506713d3 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -159,7 +159,7 @@ class ConcreteFutureImpl : public FutureImpl { if (IsFutureFinished(state_)) { return; } - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); } #endif } @@ -179,7 +179,7 @@ class ConcreteFutureImpl : public FutureImpl { if (IsFutureFinished(state_)) { return true; } - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); } return IsFutureFinished(state_); #endif diff --git a/cpp/src/arrow/util/task_group.cc b/cpp/src/arrow/util/task_group.cc index 5ac911d04da1..0f08e7bde9cb 100644 --- a/cpp/src/arrow/util/task_group.cc +++ b/cpp/src/arrow/util/task_group.cc @@ -138,7 +138,7 @@ class ThreadedTaskGroup : public TaskGroup { } #else while (!finished_ && nremaining_.load() != 0) { - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(true); + arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); } finished_ = true; #endif diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index 96fcb4279e93..d11cbf39decc 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -284,7 +284,7 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { it != globalState->all_executors.end(); ++it) { if (globalState->last_called_executor != NULL) { // always rerun loop if we have a last_called_executor, otherwise - // we drop out before everything is + // we may drop out before every executor has been checked keep_going = true; if (globalState->all_executors.count(globalState->last_called_executor) == 0 || globalState->last_called_executor == *it) { @@ -297,8 +297,12 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { continue; } SerialExecutor* exe = *it; - // don't make reentrant calls inside a serialexecutor - // or more than the number of concurrent tasks set on a threadpool + // don't make more reentrant calls inside an + // executor than the number of concurrent tasks set on a threadpool, or + // 1 in the case of a serialexecutor - + // this is because users will expect a serial executor not to be able to + // run the next task until the current one is finished (and a threadpool + // only to be able to run a certain number of tasks concurrently) if (exe->state_->tasks_running >= exe->state_->max_tasks_running) { continue; } @@ -365,7 +369,7 @@ void SerialExecutor::RunLoop() { } // now wait for anything on other executors (unless we're finished in which case it // will drop out of the outer loop - RunTasksOnAllExecutors(true); + RunTasksOnAllExecutors(); } } #endif // ARROW_ENABLE_THREADING @@ -744,7 +748,7 @@ Status ThreadPool::Shutdown(bool wait) { // needed void ThreadPool::WaitForIdle() { while (!state_->task_queue.empty()) { - RunTasksOnAllExecutors(true); + RunTasksOnAllExecutors(); } } diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index 57aeb044ae37..e88c1332e2be 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -383,10 +383,10 @@ class ARROW_EXPORT SerialExecutor : public Executor { } #ifndef ARROW_ENABLE_THREADING - // run loop until everything is done (or one go round loop if once_only=True) + // run a pending task from loop // returns true if any tasks were run in the last go round the loop (i.e. if it // returns false, all executors are waiting) - static bool RunTasksOnAllExecutors(bool once_only = false); + static bool RunTasksOnAllExecutors(); static SerialExecutor* GetCurrentExecutor(); virtual bool IsCurrentExecutor(); From 6147185daba5395ac0d02af74938cb41c52fc68c Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 14 Jul 2023 14:25:01 +0100 Subject: [PATCH 73/79] warning on too long wait on future with no tasks --- cpp/src/arrow/util/future.cc | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index a3cf506713d3..0631e17f77b1 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -155,11 +155,20 @@ class ConcreteFutureImpl : public FutureImpl { cv_.wait(lock, [this] { return IsFutureFinished(state_); }); #else + auto last_processed_time = std::chrono::steady_clock::now(); while (true) { if (IsFutureFinished(state_)) { return; } - arrow::internal::SerialExecutor::RunTasksOnAllExecutors(); + if(arrow::internal::SerialExecutor::RunTasksOnAllExecutors()==false) + { + auto this_time=std::chrono::steady_clock::now(); + if(this_time-last_processed_time < std::chrono::seconds(10)) + { + ARROW_LOG(WARNING) << "Waiting for future, but no executors have had any tasks pending for last 10 seconds"; + last_processed_time=std::chrono::steady_clock::now(); + } + } } #endif } From bc88243f99ddf425b8da52539d175ace30dcc531 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Fri, 14 Jul 2023 16:05:21 +0100 Subject: [PATCH 74/79] lint --- cpp/src/arrow/util/future.cc | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/cpp/src/arrow/util/future.cc b/cpp/src/arrow/util/future.cc index 0631e17f77b1..105d1a793a39 100644 --- a/cpp/src/arrow/util/future.cc +++ b/cpp/src/arrow/util/future.cc @@ -160,13 +160,12 @@ class ConcreteFutureImpl : public FutureImpl { if (IsFutureFinished(state_)) { return; } - if(arrow::internal::SerialExecutor::RunTasksOnAllExecutors()==false) - { - auto this_time=std::chrono::steady_clock::now(); - if(this_time-last_processed_time < std::chrono::seconds(10)) - { - ARROW_LOG(WARNING) << "Waiting for future, but no executors have had any tasks pending for last 10 seconds"; - last_processed_time=std::chrono::steady_clock::now(); + if (arrow::internal::SerialExecutor::RunTasksOnAllExecutors() == false) { + auto this_time = std::chrono::steady_clock::now(); + if (this_time - last_processed_time < std::chrono::seconds(10)) { + ARROW_LOG(WARNING) << "Waiting for future, but no executors have had any tasks " + "pending for last 10 seconds"; + last_processed_time = std::chrono::steady_clock::now(); } } } From e223f05707c245459753211846742e5501b32f4f Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Tue, 25 Jul 2023 14:47:11 -0700 Subject: [PATCH 75/79] Fix a few compiler errors introduced during rebase --- cpp/src/arrow/acero/bloom_filter_test.cc | 13 ++++++------- cpp/src/arrow/util/thread_pool.cc | 12 ++++-------- cpp/src/arrow/util/thread_pool.h | 2 +- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/cpp/src/arrow/acero/bloom_filter_test.cc b/cpp/src/arrow/acero/bloom_filter_test.cc index 1fa987279803..bad331cfd99d 100644 --- a/cpp/src/arrow/acero/bloom_filter_test.cc +++ b/cpp/src/arrow/acero/bloom_filter_test.cc @@ -468,10 +468,10 @@ TEST(BloomFilter, Basic) { test_params.push_back({0, true, false}); test_params.push_back({0, false, true}); - std::vector strategy; - strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); + std::vector strategies; + strategies.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); #if defined(ARROW_ENABLE_THREADING) && !defined(ARROW_VALGRIND) - strategy.push_back(BloomFilterBuildStrategy::PARALLEL); + strategies.push_back(BloomFilterBuildStrategy::PARALLEL); #endif static constexpr int64_t min_rows_for_large = 2 * 1024 * 1024; @@ -502,12 +502,11 @@ TEST(BloomFilter, Scaling) { num_build.push_back(1000000); num_build.push_back(4000000); - std::vector strategy; + std::vector strategies; #ifdef ARROW_ENABLE_THREADING - strategy.push_back(BloomFilterBuildStrategy::PARALLEL); -#else - strategy.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); + strategies.push_back(BloomFilterBuildStrategy::PARALLEL); #endif + strategies.push_back(BloomFilterBuildStrategy::SINGLE_THREADED); for (const auto hardware_flags : HardwareFlagsForTesting()) { for (const auto& strategy : strategies) { diff --git a/cpp/src/arrow/util/thread_pool.cc b/cpp/src/arrow/util/thread_pool.cc index d11cbf39decc..959ff2a66c9f 100644 --- a/cpp/src/arrow/util/thread_pool.cc +++ b/cpp/src/arrow/util/thread_pool.cc @@ -268,7 +268,7 @@ void SerialExecutor::RunLoop() { state_->current_thread = {}; } #else // ARROW_ENABLE_THREADING -bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { +bool SerialExecutor::RunTasksOnAllExecutors() { auto globalState = GetSerialExecutorGlobalState(); // if the previously called executor was deleted, ignore last_called_executor if (globalState->last_called_executor != NULL && @@ -323,13 +323,9 @@ bool SerialExecutor::RunTasksOnAllExecutors(bool once_only) { exe->state_->tasks_running -= 1; globalState->current_executor = old_exe; - if (once_only) { - globalState->last_called_executor = exe; - keep_going = false; - break; - } else { - keep_going = true; - } + globalState->last_called_executor = exe; + keep_going = false; + break; } } } diff --git a/cpp/src/arrow/util/thread_pool.h b/cpp/src/arrow/util/thread_pool.h index e88c1332e2be..eba79fc05d7e 100644 --- a/cpp/src/arrow/util/thread_pool.h +++ b/cpp/src/arrow/util/thread_pool.h @@ -389,7 +389,7 @@ class ARROW_EXPORT SerialExecutor : public Executor { static bool RunTasksOnAllExecutors(); static SerialExecutor* GetCurrentExecutor(); - virtual bool IsCurrentExecutor(); + bool IsCurrentExecutor() override; #endif From 702d454b8494d755a4c4db02bc9a2bbd65afddc9 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 2 Aug 2023 13:53:55 +0100 Subject: [PATCH 76/79] removed unneeded typedef --- cpp/src/arrow/testing/gtest_util.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index cb2a91740ff4..7e3bbef59817 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -734,7 +734,6 @@ void SleepFor(double seconds) { #else using Clock = std::chrono::steady_clock; using DurationDouble = std::chrono::duration; - using DurationClock = std::chrono::steady_clock::duration; auto secs_left = DurationDouble(seconds); From e5601ba2f90a2717ddb997d617ed1de7e2615c7e Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 2 Aug 2023 14:15:29 +0100 Subject: [PATCH 77/79] disable test using threads if threads are disabled --- cpp/src/parquet/encryption/key_management_test.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cpp/src/parquet/encryption/key_management_test.cc b/cpp/src/parquet/encryption/key_management_test.cc index f733c43ee1e7..6f80ab42c9a9 100644 --- a/cpp/src/parquet/encryption/key_management_test.cc +++ b/cpp/src/parquet/encryption/key_management_test.cc @@ -324,6 +324,9 @@ TEST_F(TestEncryptionKeyManagement, KeyRotationWithInternalMaterial) { } TEST_F(TestEncryptionKeyManagementMultiThread, WrapLocally) { +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif this->SetupCryptoFactory(true); this->WriteEncryptedParquetFiles(); @@ -331,6 +334,9 @@ TEST_F(TestEncryptionKeyManagementMultiThread, WrapLocally) { } TEST_F(TestEncryptionKeyManagementMultiThread, WrapOnServer) { +#ifndef ARROW_ENABLE_THREADING + GTEST_SKIP() << "Test requires threading support"; +#endif this->SetupCryptoFactory(false); this->WriteEncryptedParquetFiles(); From a4bfd804a49765a45887a05451787d54673565c5 Mon Sep 17 00:00:00 2001 From: Joe Marshall Date: Wed, 2 Aug 2023 15:19:38 +0100 Subject: [PATCH 78/79] lint fixes --- cpp/src/arrow/testing/gtest_util.cc | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/cpp/src/arrow/testing/gtest_util.cc b/cpp/src/arrow/testing/gtest_util.cc index 7e3bbef59817..c6de6b02fc8e 100644 --- a/cpp/src/arrow/testing/gtest_util.cc +++ b/cpp/src/arrow/testing/gtest_util.cc @@ -726,15 +726,12 @@ void TestInitialized(const ArrayData& array) { } void SleepFor(double seconds) { - - #ifdef ARROW_ENABLE_THREADING std::this_thread::sleep_for( std::chrono::nanoseconds(static_cast(seconds * 1e9))); #else - using Clock = std::chrono::steady_clock; - using DurationDouble = std::chrono::duration; - + using Clock = std::chrono::steady_clock; + using DurationDouble = std::chrono::duration; auto secs_left = DurationDouble(seconds); auto start_time = Clock::now(); @@ -1070,7 +1067,7 @@ class GatingTask::Impl : public std::enable_shared_from_this { Status::Invalid("Task unlock never happened - if threads are disabled you " "can't wait on gatedtask")); return; - } + } SleepABit(); auto spawn_status = executor->Spawn([this, end_time, executor, future]() { @@ -1091,11 +1088,9 @@ class GatingTask::Impl : public std::enable_shared_from_this { using DurationClock = std::chrono::steady_clock::duration; auto start_time = Clock::now(); - auto secs_left = - DurationDouble(timeout_seconds_); - auto end_time = - std::chrono::time_point_cast(start_time + - secs_left); + auto secs_left = DurationDouble(timeout_seconds_); + auto end_time = std::chrono::time_point_cast( + start_time + secs_left); auto executor = arrow::internal::GetCpuThreadPool(); auto future = Future<>::Make(); auto spawn_status = executor->Spawn([this, end_time, executor, future]() { From 6534a7484bb99b7b46281981703dacab24ca3681 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Wed, 9 Aug 2023 10:30:25 +0900 Subject: [PATCH 79/79] Revert a needless change --- cpp/src/arrow/util/async_generator_test.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/cpp/src/arrow/util/async_generator_test.cc b/cpp/src/arrow/util/async_generator_test.cc index 7a4e4e0df417..7fb99f167c60 100644 --- a/cpp/src/arrow/util/async_generator_test.cc +++ b/cpp/src/arrow/util/async_generator_test.cc @@ -1532,7 +1532,6 @@ TEST(TestAsyncUtil, ReadaheadFailedWaitForInFlight) { auto in_flight_gating_task = GatingTask::Make(); auto source = [&]() -> Future { auto count = counter++; - return DeferNotOk(thread_pool->Submit([&, count]() -> Result { if (count == 0) { failure_gating_task->Task()();