From 3417325cc2c1e2e9795472f6605327b22b00d4c2 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 16 May 2018 18:18:52 +0200 Subject: [PATCH 01/17] ARROW-2568: [Python] WIP --- cpp/src/arrow/python/arrow_to_pandas.cc | 37 +++++++++++---------- cpp/src/arrow/python/arrow_to_pandas.h | 4 +-- cpp/src/arrow/util/parallel.h | 6 ++++ python/pyarrow/feather.py | 30 ++++++++++++----- python/pyarrow/includes/libarrow.pxd | 2 +- python/pyarrow/ipc.py | 16 ++++++--- python/pyarrow/pandas_compat.py | 9 ++--- python/pyarrow/table.pxi | 30 ++++++++++------- python/pyarrow/tests/test_convert_pandas.py | 10 +++--- python/pyarrow/tests/test_feather.py | 6 ++-- python/pyarrow/tests/test_ipc.py | 8 ++--- 11 files changed, 97 insertions(+), 61 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index f8887d4d8f3d..cd48e02f4bbf 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -40,7 +40,7 @@ #include "arrow/util/decimal.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" -#include "arrow/util/parallel.h" +#include "arrow/util/thread-pool.h" #include "arrow/visitor_inline.h" #include "arrow/compute/api.h" @@ -1370,14 +1370,14 @@ class DataFrameBlockCreator { const std::shared_ptr& table, MemoryPool* pool) : table_(table), options_(options), pool_(pool) {} - Status Convert(int nthreads, PyObject** output) { + Status Convert(bool use_threads, PyObject** output) { column_types_.resize(table_->num_columns()); column_block_placement_.resize(table_->num_columns()); type_counts_.clear(); blocks_.clear(); RETURN_NOT_OK(CreateBlocks()); - RETURN_NOT_OK(WriteTableToBlocks(nthreads)); + RETURN_NOT_OK(WriteTableToBlocks(use_threads)); return GetResultList(output); } @@ -1450,23 +1450,26 @@ class DataFrameBlockCreator { return Status::OK(); } - Status WriteTableToBlocks(int nthreads) { + Status WriteTableToBlocks(bool use_threads) { auto WriteColumn = [this](int i) { std::shared_ptr block; RETURN_NOT_OK(this->GetBlock(i, &block)); return block->Write(this->table_->column(i), i, this->column_block_placement_[i]); }; - int num_tasks = table_->num_columns(); - nthreads = std::min(nthreads, num_tasks); - if (nthreads == 1) { - for (int i = 0; i < num_tasks; ++i) { - RETURN_NOT_OK(WriteColumn(i)); + arrow::internal::ThreadPool* pool = arrow::internal::CPUThreadPool(); + std::vector> futures; + for (int i = 0; i < table_->num_columns(); ++i) { + futures.push_back(pool->Submit(WriteColumn, i)); + } + auto final_status = Status::OK(); + for (auto& fut : futures) { + Status st = fut.get(); + if (!st.ok()) { + final_status = st; } - } else { - RETURN_NOT_OK(ParallelFor(nthreads, num_tasks, WriteColumn)); } - return Status::OK(); + return final_status; } Status AppendBlocks(const BlockMap& blocks, PyObject* list) { @@ -1866,14 +1869,14 @@ Status ConvertColumnToPandas(PandasOptions options, const std::shared_ptr& table, - int nthreads, MemoryPool* pool, PyObject** out) { - return ConvertTableToPandas(options, std::unordered_set(), table, nthreads, - pool, out); + bool use_threads, MemoryPool* pool, PyObject** out) { + return ConvertTableToPandas(options, std::unordered_set(), table, + use_threads, pool, out); } Status ConvertTableToPandas(PandasOptions options, const std::unordered_set& categorical_columns, - const std::shared_ptr
& table, int nthreads, + const std::shared_ptr
& table, bool use_threads, MemoryPool* pool, PyObject** out) { std::shared_ptr
current_table = table; if (!categorical_columns.empty()) { @@ -1894,7 +1897,7 @@ Status ConvertTableToPandas(PandasOptions options, } DataFrameBlockCreator helper(options, current_table, pool); - return helper.Convert(nthreads, out); + return helper.Convert(use_threads, out); } } // namespace py diff --git a/cpp/src/arrow/python/arrow_to_pandas.h b/cpp/src/arrow/python/arrow_to_pandas.h index 4819eb42c68f..ead6cd8c0946 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.h +++ b/cpp/src/arrow/python/arrow_to_pandas.h @@ -68,7 +68,7 @@ Status ConvertColumnToPandas(PandasOptions options, const std::shared_ptr& table, - int nthreads, MemoryPool* pool, PyObject** out); + bool use_threads, MemoryPool* pool, PyObject** out); /// Convert a whole table as efficiently as possible to a pandas.DataFrame. /// @@ -77,7 +77,7 @@ Status ConvertTableToPandas(PandasOptions options, const std::shared_ptr
& ARROW_EXPORT Status ConvertTableToPandas(PandasOptions options, const std::unordered_set& categorical_columns, - const std::shared_ptr
& table, int nthreads, + const std::shared_ptr
& table, bool use_threads, MemoryPool* pool, PyObject** out); } // namespace py diff --git a/cpp/src/arrow/util/parallel.h b/cpp/src/arrow/util/parallel.h index 9fec000c3ed3..e151cafc849b 100644 --- a/cpp/src/arrow/util/parallel.h +++ b/cpp/src/arrow/util/parallel.h @@ -27,6 +27,12 @@ namespace arrow { +// A parallelizer that takes a `Status(int)` function and calls it with +// arguments between 0 and `num_tasks - 1`, using the given number of +// concurrent threads. +// In most cases it's more appropriate to use the global CPU thread pool +// (see arrow/util/thread-pool.h) + template Status ParallelFor(int nthreads, int num_tasks, FUNCTION&& func) { std::vector thread_pool; diff --git a/python/pyarrow/feather.py b/python/pyarrow/feather.py index c2157ab0236b..28715e5d68e8 100644 --- a/python/pyarrow/feather.py +++ b/python/pyarrow/feather.py @@ -66,8 +66,13 @@ def read_table(self, columns=None): table = Table.from_arrays(columns, names=names) return table - def read_pandas(self, columns=None, nthreads=1): - return self.read_table(columns=columns).to_pandas(nthreads=nthreads) + def read_pandas(self, columns=None, nthreads=None, use_threads=False): + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) + return self.read_table(columns=columns).to_pandas( + use_threads=use_threads) class FeatherWriter(object): @@ -141,7 +146,7 @@ def validate_schemas(self, piece, table): .format(piece, self.schema, table.schema)) - def read_pandas(self, columns=None, nthreads=1): + def read_pandas(self, columns=None, nthreads=None, use_threads=False): """ Read multiple Parquet files as a single pandas DataFrame @@ -157,7 +162,12 @@ def read_pandas(self, columns=None, nthreads=1): pandas.DataFrame Content of the file as a pandas DataFrame (of columns) """ - return self.read_table(columns=columns).to_pandas(nthreads=nthreads) + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) + return self.read_table(columns=columns).to_pandas( + use_threads=use_threads) def write_feather(df, dest): @@ -186,7 +196,7 @@ def write_feather(df, dest): raise -def read_feather(source, columns=None, nthreads=1): +def read_feather(source, columns=None, nthreads=None, use_threads=False): """ Read a pandas.DataFrame from Feather format @@ -196,15 +206,19 @@ def read_feather(source, columns=None, nthreads=1): columns : sequence, optional Only read a specific set of columns. If not provided, all columns are read - nthreads : int, default 1 - Number of CPU threads to use when reading to pandas.DataFrame + use_threads: bool, default False + Whether to parallelize reading using multiple threads Returns ------- df : pandas.DataFrame """ + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) reader = FeatherReader(source) - return reader.read_pandas(columns=columns, nthreads=nthreads) + return reader.read_pandas(columns=columns, use_threads=use_threads) def read_table(source, columns=None): diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 9a0b4687e124..6eaee938fd97 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -959,7 +959,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: PandasOptions options, const unordered_set[c_string]& categorical_columns, const shared_ptr[CTable]& table, - int nthreads, CMemoryPool* pool, + c_bool use_threads, CMemoryPool* pool, PyObject** out) void c_set_default_memory_pool \ diff --git a/python/pyarrow/ipc.py b/python/pyarrow/ipc.py index 4081fc50e6df..c39f71787475 100644 --- a/python/pyarrow/ipc.py +++ b/python/pyarrow/ipc.py @@ -17,6 +17,8 @@ # Arrow file and stream reader/writer classes, and other messaging tools +import warnings + import pyarrow as pa from pyarrow.lib import (Message, MessageReader, # noqa @@ -168,22 +170,26 @@ def serialize_pandas(df, nthreads=None, preserve_index=True): return sink.get_result() -def deserialize_pandas(buf, nthreads=None): +def deserialize_pandas(buf, nthreads=None, use_threads=False): """Deserialize a buffer protocol compatible object into a pandas DataFrame. Parameters ---------- buf : buffer An object compatible with the buffer protocol - nthreads : int, defualt None - The number of threads to use to convert the buffer to a DataFrame, - default all CPUs + use_threads: boolean, default False + Whether to parallelize the conversion using multiple threads Returns ------- df : pandas.DataFrame """ + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) + buffer_reader = pa.BufferReader(buf) reader = pa.RecordBatchStreamReader(buffer_reader) table = reader.read_all() - return table.to_pandas(nthreads=nthreads) + return table.to_pandas(use_threads=use_threads) diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index c288c7f03a8a..63907b830e28 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -493,7 +493,7 @@ def _make_datetimetz(tz): # Converting pyarrow.Table efficiently to pandas.DataFrame -def table_to_blockmanager(options, table, memory_pool, nthreads=1, +def table_to_blockmanager(options, table, memory_pool, use_threads, categories=None): from pyarrow.compat import DatetimeTZDtype @@ -568,7 +568,7 @@ def table_to_blockmanager(options, table, memory_pool, nthreads=1, block_table.schema.get_field_index(raw_name) ) - blocks = _table_to_blocks(options, block_table, nthreads, memory_pool, + blocks = _table_to_blocks(options, block_table, use_threads, memory_pool, categories) # Construct the row index @@ -728,11 +728,12 @@ def _reconstruct_columns_from_metadata(columns, column_indexes): return pd.MultiIndex(levels=new_levels, labels=labels, names=columns.names) -def _table_to_blocks(options, block_table, nthreads, memory_pool, categories): +def _table_to_blocks(options, block_table, use_threads, memory_pool, + categories): # Part of table_to_blockmanager # Convert an arrow table to Block from the internal pandas API - result = pa.lib.table_to_blocks(options, block_table, nthreads, + result = pa.lib.table_to_blocks(options, block_table, use_threads, memory_pool, categories) # Defined above diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index c867657b9ea2..0d93013a1d85 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -16,6 +16,7 @@ # under the License. import json +import warnings from collections import OrderedDict @@ -746,7 +747,7 @@ cdef class RecordBatch: entries.append((name, column)) return OrderedDict(entries) - def to_pandas(self, nthreads=None): + def to_pandas(self, nthreads=None, use_threads=False): """ Convert the arrow::RecordBatch to a pandas DataFrame @@ -754,7 +755,11 @@ cdef class RecordBatch: ------- pandas.DataFrame """ - return Table.from_batches([self]).to_pandas(nthreads=nthreads) + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) + return Table.from_batches([self]).to_pandas(use_threads=use_threads) @classmethod def from_pandas(cls, df, Schema schema=None, bint preserve_index=True, @@ -825,7 +830,7 @@ cdef class RecordBatch: CRecordBatch.Make(schema, num_rows, c_arrays)) -def table_to_blocks(PandasOptions options, Table table, int nthreads, +def table_to_blocks(PandasOptions options, Table table, c_bool use_threads, MemoryPool memory_pool, categories): cdef: PyObject* result_obj @@ -840,7 +845,7 @@ def table_to_blocks(PandasOptions options, Table table, int nthreads, with nogil: check_status( libarrow.ConvertTableToPandas( - options, categorical_columns, c_table, nthreads, pool, + options, categorical_columns, c_table, use_threads, pool, &result_obj ) ) @@ -1148,16 +1153,12 @@ cdef class Table: def to_pandas(self, nthreads=None, strings_to_categorical=False, memory_pool=None, zero_copy_only=False, categories=None, - integer_object_nulls=False): + integer_object_nulls=False, use_threads=False): """ Convert the arrow::Table to a pandas DataFrame Parameters ---------- - nthreads : int, default max(1, multiprocessing.cpu_count() / 2) - For the default, we divide the CPU count by 2 because most modern - computers have hyperthreading turned on, so doubling the CPU count - beyond the number of physical cores does not help strings_to_categorical : boolean, default False Encode string (UTF8) and binary types to pandas.Categorical memory_pool: MemoryPool, optional @@ -1169,6 +1170,8 @@ cdef class Table: List of columns that should be returned as pandas.Categorical integer_object_nulls : boolean, default False Cast integers with nulls to objects + use_threads: boolean, default False + Whether to parallelize the conversion using multiple threads Returns ------- @@ -1177,15 +1180,18 @@ cdef class Table: cdef: PandasOptions options + if nthreads is not None: + warnings.warn("`nthreads` argument is ignored, " + "pass `use_threads` instead", DeprecationWarning, + stacklevel=2) + options = PandasOptions( strings_to_categorical=strings_to_categorical, zero_copy_only=zero_copy_only, integer_object_nulls=integer_object_nulls) self._check_nullptr() - if nthreads is None: - nthreads = cpu_count() mgr = pdcompat.table_to_blockmanager(options, self, memory_pool, - nthreads, categories) + use_threads, categories) return pd.DataFrame(mgr) def to_pydict(self): diff --git a/python/pyarrow/tests/test_convert_pandas.py b/python/pyarrow/tests/test_convert_pandas.py index bdb84c7d6bae..6bdbcca01c6a 100644 --- a/python/pyarrow/tests/test_convert_pandas.py +++ b/python/pyarrow/tests/test_convert_pandas.py @@ -60,7 +60,7 @@ def _alltypes_example(size=100): }) -def _check_pandas_roundtrip(df, expected=None, nthreads=1, +def _check_pandas_roundtrip(df, expected=None, use_threads=False, expected_schema=None, check_dtype=True, schema=None, preserve_index=False, @@ -68,9 +68,9 @@ def _check_pandas_roundtrip(df, expected=None, nthreads=1, klass = pa.RecordBatch if as_batch else pa.Table table = klass.from_pandas(df, schema=schema, preserve_index=preserve_index, - nthreads=nthreads) + nthreads=2 if use_threads else 1) - result = table.to_pandas(nthreads=nthreads) + result = table.to_pandas(use_threads=use_threads) if expected_schema: assert table.schema.equals(expected_schema) if expected is None: @@ -1836,8 +1836,8 @@ def test_empty_arrays(self): def test_threaded_conversion(self): df = _alltypes_example() - _check_pandas_roundtrip(df, nthreads=2) - _check_pandas_roundtrip(df, nthreads=2, as_batch=True) + _check_pandas_roundtrip(df, use_threads=True) + _check_pandas_roundtrip(df, use_threads=True, as_batch=True) def test_category(self): repeats = 5 diff --git a/python/pyarrow/tests/test_feather.py b/python/pyarrow/tests/test_feather.py index 46e4e5ffcc1f..1fcc608e27a7 100644 --- a/python/pyarrow/tests/test_feather.py +++ b/python/pyarrow/tests/test_feather.py @@ -65,7 +65,7 @@ def _get_null_counts(self, path, columns=None): def _check_pandas_roundtrip(self, df, expected=None, path=None, columns=None, null_counts=None, - nthreads=1): + use_threads=False): if path is None: path = random_path() @@ -74,7 +74,7 @@ def _check_pandas_roundtrip(self, df, expected=None, path=None, if not os.path.exists(path): raise Exception('file not written') - result = read_feather(path, columns, nthreads=nthreads) + result = read_feather(path, columns, use_threads=use_threads) if expected is None: expected = df @@ -384,7 +384,7 @@ def test_multithreaded_read(self): data = {'c{0}'.format(i): [''] * 10 for i in range(100)} df = pd.DataFrame(data) - self._check_pandas_roundtrip(df, nthreads=4) + self._check_pandas_roundtrip(df, use_threads=True) def test_nan_as_null(self): # Create a nan that is not numpy.nan diff --git a/python/pyarrow/tests/test_ipc.py b/python/pyarrow/tests/test_ipc.py index c31c32251d02..07de19fc99a6 100644 --- a/python/pyarrow/tests/test_ipc.py +++ b/python/pyarrow/tests/test_ipc.py @@ -406,9 +406,9 @@ def test_get_record_batch_size(): assert pa.get_record_batch_size(batch) > (N * itemsize) -def _check_serialize_pandas_round_trip(df, nthreads=1): - buf = pa.serialize_pandas(df, nthreads=nthreads) - result = pa.deserialize_pandas(buf, nthreads=nthreads) +def _check_serialize_pandas_round_trip(df, use_threads=False): + buf = pa.serialize_pandas(df, nthreads=2 if use_threads else 1) + result = pa.deserialize_pandas(buf, use_threads=use_threads) assert_frame_equal(result, df) @@ -429,7 +429,7 @@ def test_pandas_serialize_round_trip_nthreads(): {'foo': [1.5, 1.6, 1.7], 'bar': list('abc')}, index=index, columns=columns ) - _check_serialize_pandas_round_trip(df, nthreads=2) + _check_serialize_pandas_round_trip(df, use_threads=True) def test_pandas_serialize_round_trip_multi_index(): From 50310b8860dcf97367c297ae054f43ccff886f0b Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 18:19:35 +0200 Subject: [PATCH 02/17] Add API function to get desired ThreadPool capacity --- cpp/src/arrow/util/thread-pool-test.cc | 18 +++++++++++++++--- cpp/src/arrow/util/thread-pool.cc | 9 +++++++++ cpp/src/arrow/util/thread-pool.h | 12 +++++++++++- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool-test.cc b/cpp/src/arrow/util/thread-pool-test.cc index 42bbe6ea668d..387d71923ba0 100644 --- a/cpp/src/arrow/util/thread-pool-test.cc +++ b/cpp/src/arrow/util/thread-pool-test.cc @@ -223,21 +223,31 @@ TEST_F(TestThreadPool, QuickShutdown) { TEST_F(TestThreadPool, SetCapacity) { auto pool = this->MakeThreadPool(3); ASSERT_EQ(pool->GetCapacity(), 3); + ASSERT_EQ(pool->GetActualCapacity(), 3); + ASSERT_OK(pool->SetCapacity(5)); ASSERT_EQ(pool->GetCapacity(), 5); + ASSERT_EQ(pool->GetActualCapacity(), 5); + ASSERT_OK(pool->SetCapacity(2)); - // Wait for workers to wake up and secede - busy_wait(0.5, [&] { return pool->GetCapacity() == 2; }); ASSERT_EQ(pool->GetCapacity(), 2); + // Wait for workers to wake up and secede + busy_wait(0.5, [&] { return pool->GetActualCapacity() == 2; }); + ASSERT_EQ(pool->GetActualCapacity(), 2); + ASSERT_OK(pool->SetCapacity(5)); ASSERT_EQ(pool->GetCapacity(), 5); + ASSERT_EQ(pool->GetActualCapacity(), 5); + // Downsize while tasks are pending for (int i = 0; i < 10; ++i) { ASSERT_OK(pool->Spawn(std::bind(sleep_for, 0.01 /* seconds */))); } ASSERT_OK(pool->SetCapacity(2)); - busy_wait(0.5, [&] { return pool->GetCapacity() == 2; }); ASSERT_EQ(pool->GetCapacity(), 2); + busy_wait(0.5, [&] { return pool->GetActualCapacity() == 2; }); + ASSERT_EQ(pool->GetActualCapacity(), 2); + // Ensure nothing got stuck ASSERT_OK(pool->Shutdown()); } @@ -277,6 +287,8 @@ TEST(TestGlobalThreadPool, Capacity) { auto pool = CPUThreadPool(); size_t capacity = pool->GetCapacity(); ASSERT_GT(capacity, 0); + ASSERT_EQ(pool->GetActualCapacity(), capacity); + ASSERT_EQ(GetCPUThreadPoolCapacity(), capacity); // Exercise default capacity heuristic ASSERT_OK(DelEnvVar("OMP_NUM_THREADS")); diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 0e264f3e0e50..4a1e377e7cfc 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -52,6 +52,11 @@ Status ThreadPool::SetCapacity(size_t threads) { } size_t ThreadPool::GetCapacity() { + std::unique_lock lock(mutex_); + return desired_capacity_; +} + +size_t ThreadPool::GetActualCapacity() { std::unique_lock lock(mutex_); return workers_.size(); } @@ -216,6 +221,10 @@ ThreadPool* CPUThreadPool() { } // namespace internal +size_t GetCPUThreadPoolCapacity() { + return internal::CPUThreadPool()->GetCapacity(); +} + Status SetCPUThreadPoolCapacity(size_t threads) { return internal::CPUThreadPool()->SetCapacity(threads); } diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index d426cbbe0b46..bc25cff2c043 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -36,6 +36,11 @@ namespace arrow { +// Get the number of worker threads used by the process-global thread pool +// for CPU-bound tasks. This is an idealized number, the actual number +// may lag a bit. +ARROW_EXPORT size_t GetCPUThreadPoolCapacity(); + // Set the number of worker threads used by the process-global thread pool // for CPU-bound tasks. ARROW_EXPORT Status SetCPUThreadPoolCapacity(size_t threads); @@ -67,6 +72,11 @@ class ThreadPool { // Destroy thread pool; the pool will first be shut down ~ThreadPool(); + // Return the desired number of worker threads. + // The actual number of workers may lag a bit before being adjusted to + // match this value. + size_t GetCapacity(); + // Dynamically change the number of worker threads. // This function returns quickly, but it may take more time before the // thread count is fully adjusted. @@ -125,7 +135,7 @@ class ThreadPool { // Launch a given number of additional workers void LaunchWorkersUnlocked(size_t threads); void WorkerLoop(std::list::iterator it); - size_t GetCapacity(); + size_t GetActualCapacity(); std::mutex mutex_; std::condition_variable cv_; From 172fba37075ee9c8b41317127502cbd213bcb5d2 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 18:33:40 +0200 Subject: [PATCH 03/17] Use C++ API, rather than multiprocessing, in pyarrow.{cpu_count,set_cpu_count} --- python/pyarrow/_config.pyx | 57 ---------------------------- python/pyarrow/includes/libarrow.pxd | 5 +++ python/pyarrow/lib.pyx | 30 +++++++-------- python/pyarrow/tests/test_misc.py | 10 +++++ 4 files changed, 29 insertions(+), 73 deletions(-) delete mode 100644 python/pyarrow/_config.pyx diff --git a/python/pyarrow/_config.pyx b/python/pyarrow/_config.pyx deleted file mode 100644 index bc9f36d8e50c..000000000000 --- a/python/pyarrow/_config.pyx +++ /dev/null @@ -1,57 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# cython: profile=False -# distutils: language = c++ -# cython: embedsignature = True - -import numpy as np -import multiprocessing -import os - -cdef extern from 'arrow/python/init.h': - int arrow_init_numpy() except -1 - -cdef extern from 'arrow/python/config.h' namespace 'arrow::py': - void set_numpy_nan(object o) - -arrow_init_numpy() - -set_numpy_nan(np.nan) - -cdef int CPU_COUNT = int( - os.environ.get('OMP_NUM_THREADS', - max(multiprocessing.cpu_count() // 2, 1))) - - -def cpu_count(): - """ - Returns - ------- - count : Number of CPUs to use by default in parallel operations. Default is - max(1, multiprocessing.cpu_count() / 2), but can be overridden by the - OMP_NUM_THREADS environment variable. For the default, we divide the CPU - count by 2 because most modern computers have hyperthreading turned on, - so doubling the CPU count beyond the number of physical cores does not - help. - """ - return CPU_COUNT - - -def set_cpu_count(count): - global CPU_COUNT - CPU_COUNT = max(int(count), 1) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 6eaee938fd97..0669ed48ddb3 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1045,3 +1045,8 @@ cdef extern from 'arrow/util/compression.h' namespace 'arrow' nogil: int64_t* output_length) int64_t MaxCompressedLen(int64_t input_len, const uint8_t* input) + + +cdef extern from 'arrow/util/thread-pool.h' namespace 'arrow' nogil: + size_t GetCPUThreadPoolCapacity() + CStatus SetCPUThreadPoolCapacity(size_t threads) diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index 4c22fc42ef0f..d5c9d8fe8870 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -36,28 +36,26 @@ cimport cpython as cp arrow_init_numpy() set_numpy_nan(np.nan) -cdef int CPU_COUNT = int( - os.environ.get('OMP_NUM_THREADS', - max(multiprocessing.cpu_count() // 2, 1))) - def cpu_count(): """ - Returns - ------- - count : Number of CPUs to use by default in parallel operations. Default is - max(1, multiprocessing.cpu_count() / 2), but can be overridden by the - OMP_NUM_THREADS environment variable. For the default, we divide the CPU - count by 2 because most modern computers have hyperthreading turned on, - so doubling the CPU count beyond the number of physical cores does not - help. + Return the number of threads to use in parallel operations. + + The number of threads is determined at startup by inspecting the + OMP_NUM_THREADS and OMP_THREAD_LIMIT environment variables. If neither + is present, it will default to the number of hardware threads on the + system. It can be modified at runtime by calling set_cpu_count(). """ - return CPU_COUNT + return GetCPUThreadPoolCapacity() -def set_cpu_count(count): - global CPU_COUNT - CPU_COUNT = max(int(count), 1) +def set_cpu_count(size_t count): + """ + Set the number of threads to use in parallel operations. + """ + if count < 1: + raise ValueError("CPU count must be strictly positive") + check_status(SetCPUThreadPoolCapacity(count)) Type_NA = _Type_NA diff --git a/python/pyarrow/tests/test_misc.py b/python/pyarrow/tests/test_misc.py index 55787f135943..28553a0cf6ae 100644 --- a/python/pyarrow/tests/test_misc.py +++ b/python/pyarrow/tests/test_misc.py @@ -23,3 +23,13 @@ def test_get_include(): include_dir = pa.get_include() assert os.path.exists(os.path.join(include_dir, 'arrow', 'api.h')) + + +def test_cpu_count(): + n = pa.cpu_count() + assert n > 0 + try: + pa.set_cpu_count(n + 5) + assert pa.cpu_count() == n + 5 + finally: + pa.set_cpu_count(n) From fcca62f5ecae584fc50267d2c529f9b7db334fe5 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 18:46:05 +0200 Subject: [PATCH 04/17] Emit FutureWarning (which is visible by default) rather than DeprecationWarning --- python/pyarrow/feather.py | 8 ++++---- python/pyarrow/ipc.py | 2 +- python/pyarrow/table.pxi | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/python/pyarrow/feather.py b/python/pyarrow/feather.py index 28715e5d68e8..e91cb2d419c4 100644 --- a/python/pyarrow/feather.py +++ b/python/pyarrow/feather.py @@ -45,7 +45,7 @@ def __init__(self, source): def read(self, *args, **kwargs): warnings.warn("read has been deprecated. Use read_pandas instead.", - DeprecationWarning) + FutureWarning, stacklevel=2) return self.read_pandas(*args, **kwargs) def read_table(self, columns=None): @@ -69,7 +69,7 @@ def read_table(self, columns=None): def read_pandas(self, columns=None, nthreads=None, use_threads=False): if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) return self.read_table(columns=columns).to_pandas( use_threads=use_threads) @@ -164,7 +164,7 @@ def read_pandas(self, columns=None, nthreads=None, use_threads=False): """ if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) return self.read_table(columns=columns).to_pandas( use_threads=use_threads) @@ -215,7 +215,7 @@ def read_feather(source, columns=None, nthreads=None, use_threads=False): """ if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) reader = FeatherReader(source) return reader.read_pandas(columns=columns, use_threads=use_threads) diff --git a/python/pyarrow/ipc.py b/python/pyarrow/ipc.py index c39f71787475..4d767a37be34 100644 --- a/python/pyarrow/ipc.py +++ b/python/pyarrow/ipc.py @@ -186,7 +186,7 @@ def deserialize_pandas(buf, nthreads=None, use_threads=False): """ if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) buffer_reader = pa.BufferReader(buf) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 0d93013a1d85..b3cfb81359d0 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -757,7 +757,7 @@ cdef class RecordBatch: """ if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) return Table.from_batches([self]).to_pandas(use_threads=use_threads) @@ -1182,7 +1182,7 @@ cdef class Table: if nthreads is not None: warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", DeprecationWarning, + "pass `use_threads` instead", FutureWarning, stacklevel=2) options = PandasOptions( From 6985afe60a70223a53602dec20baebcb5ee6b0da Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 18:47:34 +0200 Subject: [PATCH 05/17] Lint --- cpp/src/arrow/util/thread-pool.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 4a1e377e7cfc..92862d154833 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -221,9 +221,7 @@ ThreadPool* CPUThreadPool() { } // namespace internal -size_t GetCPUThreadPoolCapacity() { - return internal::CPUThreadPool()->GetCapacity(); -} +size_t GetCPUThreadPoolCapacity() { return internal::CPUThreadPool()->GetCapacity(); } Status SetCPUThreadPoolCapacity(size_t threads) { return internal::CPUThreadPool()->SetCapacity(threads); From d4eb8d47c8ccf6010626dcf96b3578c3e288b733 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 20:50:26 +0200 Subject: [PATCH 06/17] Export ThreadPool and CPUThreadPool() --- cpp/src/arrow/util/thread-pool.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index bc25cff2c043..3d44a19f56fb 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -64,7 +64,7 @@ struct packaged_task_wrapper { } // namespace detail -class ThreadPool { +class ARROW_EXPORT ThreadPool { public: // Construct a thread pool with the given number of worker threads static Status Make(size_t threads, std::shared_ptr* out); @@ -154,7 +154,7 @@ class ThreadPool { }; // Return the process-global thread pool for CPU-bound tasks. -ThreadPool* CPUThreadPool(); +ARROW_EXPORT ThreadPool* CPUThreadPool(); } // namespace internal } // namespace arrow From 616697551d02ae1e7f0a5131848c7e34e3a93267 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 20:59:43 +0200 Subject: [PATCH 07/17] Rename CPUThreadPool() to GetCpuThreadPool() --- cpp/src/arrow/python/arrow_to_pandas.cc | 2 +- cpp/src/arrow/util/memory.h | 2 +- cpp/src/arrow/util/thread-pool-test.cc | 4 ++-- cpp/src/arrow/util/thread-pool.cc | 8 ++++---- cpp/src/arrow/util/thread-pool.h | 6 +++--- cpp/src/plasma/client.cc | 2 +- python/pyarrow/includes/libarrow.pxd | 4 ++-- python/pyarrow/lib.pyx | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index cd48e02f4bbf..16de5cfbab1c 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -1457,7 +1457,7 @@ class DataFrameBlockCreator { return block->Write(this->table_->column(i), i, this->column_block_placement_[i]); }; - arrow::internal::ThreadPool* pool = arrow::internal::CPUThreadPool(); + arrow::internal::ThreadPool* pool = arrow::internal::GetCpuThreadPool(); std::vector> futures; for (int i = 0; i < table_->num_columns(); ++i) { futures.push_back(pool->Submit(WriteColumn, i)); diff --git a/cpp/src/arrow/util/memory.h b/cpp/src/arrow/util/memory.h index f391d273cb58..56fadca63d51 100644 --- a/cpp/src/arrow/util/memory.h +++ b/cpp/src/arrow/util/memory.h @@ -36,7 +36,7 @@ uint8_t* pointer_logical_and(const uint8_t* address, uintptr_t bits) { void parallel_memcopy(uint8_t* dst, const uint8_t* src, int64_t nbytes, uintptr_t block_size, int num_threads) { // XXX This function is really using `num_threads + 1` threads. - auto pool = CPUThreadPool(); + auto pool = GetCpuThreadPool(); uint8_t* left = pointer_logical_and(src + block_size - 1, ~(block_size - 1)); uint8_t* right = pointer_logical_and(src + nbytes, ~(block_size - 1)); diff --git a/cpp/src/arrow/util/thread-pool-test.cc b/cpp/src/arrow/util/thread-pool-test.cc index 387d71923ba0..1a110c6b5715 100644 --- a/cpp/src/arrow/util/thread-pool-test.cc +++ b/cpp/src/arrow/util/thread-pool-test.cc @@ -284,11 +284,11 @@ TEST_F(TestThreadPool, Submit) { TEST(TestGlobalThreadPool, Capacity) { // Sanity check - auto pool = CPUThreadPool(); + auto pool = GetCpuThreadPool(); size_t capacity = pool->GetCapacity(); ASSERT_GT(capacity, 0); ASSERT_EQ(pool->GetActualCapacity(), capacity); - ASSERT_EQ(GetCPUThreadPoolCapacity(), capacity); + ASSERT_EQ(GetCpuThreadPoolCapacity(), capacity); // Exercise default capacity heuristic ASSERT_OK(DelEnvVar("OMP_NUM_THREADS")); diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 92862d154833..7afb53fa8e0c 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -214,17 +214,17 @@ static std::shared_ptr MakePoolWithDefaultCapacity() { return pool; } -ThreadPool* CPUThreadPool() { +ThreadPool* GetCpuThreadPool() { static std::shared_ptr singleton = MakePoolWithDefaultCapacity(); return singleton.get(); } } // namespace internal -size_t GetCPUThreadPoolCapacity() { return internal::CPUThreadPool()->GetCapacity(); } +size_t GetCpuThreadPoolCapacity() { return internal::GetCpuThreadPool()->GetCapacity(); } -Status SetCPUThreadPoolCapacity(size_t threads) { - return internal::CPUThreadPool()->SetCapacity(threads); +Status SetCpuThreadPoolCapacity(size_t threads) { + return internal::GetCpuThreadPool()->SetCapacity(threads); } } // namespace arrow diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index 3d44a19f56fb..c315936bf17e 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -39,11 +39,11 @@ namespace arrow { // Get the number of worker threads used by the process-global thread pool // for CPU-bound tasks. This is an idealized number, the actual number // may lag a bit. -ARROW_EXPORT size_t GetCPUThreadPoolCapacity(); +ARROW_EXPORT size_t GetCpuThreadPoolCapacity(); // Set the number of worker threads used by the process-global thread pool // for CPU-bound tasks. -ARROW_EXPORT Status SetCPUThreadPoolCapacity(size_t threads); +ARROW_EXPORT Status SetCpuThreadPoolCapacity(size_t threads); namespace internal { @@ -154,7 +154,7 @@ class ARROW_EXPORT ThreadPool { }; // Return the process-global thread pool for CPU-bound tasks. -ARROW_EXPORT ThreadPool* CPUThreadPool(); +ARROW_EXPORT ThreadPool* GetCpuThreadPool(); } // namespace internal } // namespace arrow diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 43e27e0b2e19..30d2e43d32b5 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -698,7 +698,7 @@ bool PlasmaClient::Impl::compute_object_hash_parallel(XXH64_state_t* hash_state, int64_t nbytes) { // Note that this function will likely be faster if the address of data is // aligned on a 64-byte boundary. - auto pool = arrow::internal::CPUThreadPool(); + auto pool = arrow::internal::GetCpuThreadPool(); const int num_threads = kHashingConcurrency; uint64_t threadhash[num_threads + 1]; diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 0669ed48ddb3..9db65f80dbf0 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1048,5 +1048,5 @@ cdef extern from 'arrow/util/compression.h' namespace 'arrow' nogil: cdef extern from 'arrow/util/thread-pool.h' namespace 'arrow' nogil: - size_t GetCPUThreadPoolCapacity() - CStatus SetCPUThreadPoolCapacity(size_t threads) + size_t GetCpuThreadPoolCapacity() + CStatus SetCpuThreadPoolCapacity(size_t threads) diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index d5c9d8fe8870..72ccd88d2a27 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -46,7 +46,7 @@ def cpu_count(): is present, it will default to the number of hardware threads on the system. It can be modified at runtime by calling set_cpu_count(). """ - return GetCPUThreadPoolCapacity() + return GetCpuThreadPoolCapacity() def set_cpu_count(size_t count): @@ -55,7 +55,7 @@ def set_cpu_count(size_t count): """ if count < 1: raise ValueError("CPU count must be strictly positive") - check_status(SetCPUThreadPoolCapacity(count)) + check_status(SetCpuThreadPoolCapacity(count)) Type_NA = _Type_NA From 6b6f64a1e5f4854442ccb3733713f272b1afca18 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 21:08:06 +0200 Subject: [PATCH 08/17] Make ThreadPool capacity an int, not a size_t --- cpp/src/arrow/util/thread-pool.cc | 32 ++++++++++++++-------------- cpp/src/arrow/util/thread-pool.h | 19 +++++++++-------- python/pyarrow/includes/libarrow.pxd | 4 ++-- python/pyarrow/lib.pyx | 2 +- 4 files changed, 29 insertions(+), 28 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 7afb53fa8e0c..81641cd15b4a 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -30,7 +30,7 @@ ThreadPool::ThreadPool() ThreadPool::~ThreadPool() { ARROW_UNUSED(Shutdown(false /* wait */)); } -Status ThreadPool::SetCapacity(size_t threads) { +Status ThreadPool::SetCapacity(int threads) { std::unique_lock lock(mutex_); if (please_shutdown_) { return Status::Invalid("operation forbidden during or after shutdown"); @@ -41,9 +41,9 @@ Status ThreadPool::SetCapacity(size_t threads) { CollectFinishedWorkersUnlocked(); desired_capacity_ = threads; - int64_t diff = desired_capacity_ - workers_.size(); + int diff = static_cast(desired_capacity_ - workers_.size()); if (diff > 0) { - LaunchWorkersUnlocked(static_cast(diff)); + LaunchWorkersUnlocked(diff); } else if (diff < 0) { // Wake threads to ask them to stop cv_.notify_all(); @@ -51,12 +51,12 @@ Status ThreadPool::SetCapacity(size_t threads) { return Status::OK(); } -size_t ThreadPool::GetCapacity() { +int ThreadPool::GetCapacity() { std::unique_lock lock(mutex_); return desired_capacity_; } -size_t ThreadPool::GetActualCapacity() { +int ThreadPool::GetActualCapacity() { std::unique_lock lock(mutex_); return workers_.size(); } @@ -88,8 +88,8 @@ void ThreadPool::CollectFinishedWorkersUnlocked() { finished_workers_.clear(); } -void ThreadPool::LaunchWorkersUnlocked(size_t threads) { - for (size_t i = 0; i < threads; i++) { +void ThreadPool::LaunchWorkersUnlocked(int threads) { + for (int i = 0; i < threads; i++) { workers_.emplace_back(); auto it = --workers_.end(); *it = std::thread([this, it] { WorkerLoop(it); }); @@ -113,7 +113,7 @@ void ThreadPool::WorkerLoop(std::list::iterator it) { // If too many threads, secede from the pool. // We check this opportunistically at each loop iteration since // it releases the lock below. - if (workers_.size() > desired_capacity_) { + if (workers_.size() > static_cast(desired_capacity_)) { break; } { @@ -125,7 +125,7 @@ void ThreadPool::WorkerLoop(std::list::iterator it) { lock.lock(); } // Now either the queue is empty *or* a quick shutdown was requested - if (please_shutdown_ || workers_.size() > desired_capacity_) { + if (please_shutdown_ || workers_.size() > static_cast(desired_capacity_)) { break; } // Wait for next wakeup @@ -161,7 +161,7 @@ Status ThreadPool::SpawnReal(std::function task) { return Status::OK(); } -Status ThreadPool::Make(size_t threads, std::shared_ptr* out) { +Status ThreadPool::Make(int threads, std::shared_ptr* out) { auto pool = std::shared_ptr(new ThreadPool()); RETURN_NOT_OK(pool->SetCapacity(threads)); *out = std::move(pool); @@ -171,7 +171,7 @@ Status ThreadPool::Make(size_t threads, std::shared_ptr* out) { // ---------------------------------------------------------------------- // Global thread pool -static size_t ParseOMPEnvVar(const char* name) { +static int ParseOMPEnvVar(const char* name) { // OMP_NUM_THREADS is a comma-separated list of positive integers. // We are only interested in the first (top-level) number. std::string str; @@ -183,14 +183,14 @@ static size_t ParseOMPEnvVar(const char* name) { str = str.substr(0, first_comma); } try { - return static_cast(std::max(0LL, std::stoll(str))); + return std::max(0, std::stoi(str)); } catch (...) { return 0; } } -size_t ThreadPool::DefaultCapacity() { - size_t capacity, limit; +int ThreadPool::DefaultCapacity() { + int capacity, limit; capacity = ParseOMPEnvVar("OMP_NUM_THREADS"); if (capacity == 0) { capacity = std::thread::hardware_concurrency(); @@ -221,9 +221,9 @@ ThreadPool* GetCpuThreadPool() { } // namespace internal -size_t GetCpuThreadPoolCapacity() { return internal::GetCpuThreadPool()->GetCapacity(); } +int GetCpuThreadPoolCapacity() { return internal::GetCpuThreadPool()->GetCapacity(); } -Status SetCpuThreadPoolCapacity(size_t threads) { +Status SetCpuThreadPoolCapacity(int threads) { return internal::GetCpuThreadPool()->SetCapacity(threads); } diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index c315936bf17e..a7f3d6452121 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -39,11 +39,11 @@ namespace arrow { // Get the number of worker threads used by the process-global thread pool // for CPU-bound tasks. This is an idealized number, the actual number // may lag a bit. -ARROW_EXPORT size_t GetCpuThreadPoolCapacity(); +ARROW_EXPORT int GetCpuThreadPoolCapacity(); // Set the number of worker threads used by the process-global thread pool // for CPU-bound tasks. -ARROW_EXPORT Status SetCpuThreadPoolCapacity(size_t threads); +ARROW_EXPORT Status SetCpuThreadPoolCapacity(int threads); namespace internal { @@ -67,7 +67,7 @@ struct packaged_task_wrapper { class ARROW_EXPORT ThreadPool { public: // Construct a thread pool with the given number of worker threads - static Status Make(size_t threads, std::shared_ptr* out); + static Status Make(int threads, std::shared_ptr* out); // Destroy thread pool; the pool will first be shut down ~ThreadPool(); @@ -75,16 +75,16 @@ class ARROW_EXPORT ThreadPool { // Return the desired number of worker threads. // The actual number of workers may lag a bit before being adjusted to // match this value. - size_t GetCapacity(); + int GetCapacity(); // Dynamically change the number of worker threads. // This function returns quickly, but it may take more time before the // thread count is fully adjusted. - Status SetCapacity(size_t threads); + Status SetCapacity(int threads); // Heuristic for the default capacity of a thread pool for CPU-bound tasks. // This is exposed as a static method to help with testing. - static size_t DefaultCapacity(); + static int DefaultCapacity(); // Shutdown the pool. Once the pool starts shutting down, new tasks // cannot be submitted anymore. @@ -116,6 +116,7 @@ class ARROW_EXPORT ThreadPool { Status st = SpawnReal(detail::packaged_task_wrapper(std::move(task))); if (!st.ok()) { + // This happens when Submit() is called after Shutdown() throw std::runtime_error(st.ToString()); } return fut; @@ -133,9 +134,9 @@ class ARROW_EXPORT ThreadPool { // Collect finished worker threads, making sure the OS threads have exited void CollectFinishedWorkersUnlocked(); // Launch a given number of additional workers - void LaunchWorkersUnlocked(size_t threads); + void LaunchWorkersUnlocked(int threads); void WorkerLoop(std::list::iterator it); - size_t GetActualCapacity(); + int GetActualCapacity(); std::mutex mutex_; std::condition_variable cv_; @@ -147,7 +148,7 @@ class ARROW_EXPORT ThreadPool { std::deque> pending_tasks_; // Desired number of threads - size_t desired_capacity_; + int desired_capacity_; // Are we shutting down? bool please_shutdown_; bool quick_shutdown_; diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 9db65f80dbf0..586f27885676 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1048,5 +1048,5 @@ cdef extern from 'arrow/util/compression.h' namespace 'arrow' nogil: cdef extern from 'arrow/util/thread-pool.h' namespace 'arrow' nogil: - size_t GetCpuThreadPoolCapacity() - CStatus SetCpuThreadPoolCapacity(size_t threads) + int GetCpuThreadPoolCapacity() + CStatus SetCpuThreadPoolCapacity(int threads) diff --git a/python/pyarrow/lib.pyx b/python/pyarrow/lib.pyx index 72ccd88d2a27..9c661dbc3554 100644 --- a/python/pyarrow/lib.pyx +++ b/python/pyarrow/lib.pyx @@ -49,7 +49,7 @@ def cpu_count(): return GetCpuThreadPoolCapacity() -def set_cpu_count(size_t count): +def set_cpu_count(int count): """ Set the number of threads to use in parallel operations. """ From 6b685406e305b4b7c9bfdcd421b21cfcae40578e Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 23 May 2018 21:21:03 +0200 Subject: [PATCH 09/17] Fix MSVC warning --- cpp/src/arrow/python/python-test.cc | 3 ++- cpp/src/arrow/util/thread-pool-test.cc | 8 ++++---- cpp/src/arrow/util/thread-pool.cc | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/cpp/src/arrow/python/python-test.cc b/cpp/src/arrow/python/python-test.cc index 60da08b6d473..cbab897c4337 100644 --- a/cpp/src/arrow/python/python-test.cc +++ b/cpp/src/arrow/python/python-test.cc @@ -239,7 +239,8 @@ TEST(PandasConversionTest, TestObjectBlockWriteFails) { Py_BEGIN_ALLOW_THREADS; PandasOptions options; MemoryPool* pool = default_memory_pool(); - ASSERT_RAISES(UnknownError, ConvertTableToPandas(options, table, 2, pool, &out)); + ASSERT_RAISES(UnknownError, + ConvertTableToPandas(options, table, true /* use_threads */, pool, &out)); Py_END_ALLOW_THREADS; } diff --git a/cpp/src/arrow/util/thread-pool-test.cc b/cpp/src/arrow/util/thread-pool-test.cc index 1a110c6b5715..a70f0164e832 100644 --- a/cpp/src/arrow/util/thread-pool-test.cc +++ b/cpp/src/arrow/util/thread-pool-test.cc @@ -127,7 +127,7 @@ class TestThreadPool : public ::testing::Test { std::shared_ptr MakeThreadPool() { return MakeThreadPool(4); } - std::shared_ptr MakeThreadPool(size_t threads) { + std::shared_ptr MakeThreadPool(int threads) { std::shared_ptr pool; Status st = ThreadPool::Make(threads, &pool); return pool; @@ -163,7 +163,7 @@ class TestThreadPool : public ::testing::Test { TEST_F(TestThreadPool, ConstructDestruct) { // Stress shutdown-at-destruction logic - for (size_t threads : {1, 2, 3, 8, 32, 70}) { + for (int threads : {1, 2, 3, 8, 32, 70}) { auto pool = this->MakeThreadPool(threads); } } @@ -285,7 +285,7 @@ TEST_F(TestThreadPool, Submit) { TEST(TestGlobalThreadPool, Capacity) { // Sanity check auto pool = GetCpuThreadPool(); - size_t capacity = pool->GetCapacity(); + int capacity = pool->GetCapacity(); ASSERT_GT(capacity, 0); ASSERT_EQ(pool->GetActualCapacity(), capacity); ASSERT_EQ(GetCpuThreadPoolCapacity(), capacity); @@ -293,7 +293,7 @@ TEST(TestGlobalThreadPool, Capacity) { // Exercise default capacity heuristic ASSERT_OK(DelEnvVar("OMP_NUM_THREADS")); ASSERT_OK(DelEnvVar("OMP_THREAD_LIMIT")); - size_t hw_capacity = std::thread::hardware_concurrency(); + int hw_capacity = std::thread::hardware_concurrency(); ASSERT_EQ(ThreadPool::DefaultCapacity(), hw_capacity); ASSERT_OK(SetEnvVar("OMP_NUM_THREADS", "13")); ASSERT_EQ(ThreadPool::DefaultCapacity(), 13); diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 81641cd15b4a..1c4fe9e1c29f 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -58,7 +58,7 @@ int ThreadPool::GetCapacity() { int ThreadPool::GetActualCapacity() { std::unique_lock lock(mutex_); - return workers_.size(); + return static_cast(workers_.size()); } Status ThreadPool::Shutdown(bool wait) { From 9639707600bf71d10a29e34e720141f5b986557e Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 11:30:22 +0200 Subject: [PATCH 10/17] Factor out deprecation logic --- python/pyarrow/feather.py | 17 +++++------------ python/pyarrow/ipc.py | 8 ++------ python/pyarrow/table.pxi | 13 ++++--------- python/pyarrow/util.py | 10 ++++++++++ 4 files changed, 21 insertions(+), 27 deletions(-) diff --git a/python/pyarrow/feather.py b/python/pyarrow/feather.py index e91cb2d419c4..26f22dac7ed8 100644 --- a/python/pyarrow/feather.py +++ b/python/pyarrow/feather.py @@ -26,6 +26,8 @@ from pyarrow.lib import FeatherError # noqa from pyarrow.lib import RecordBatch, Table, concat_tables import pyarrow.lib as ext +from .util import _deprecate_nthreads + try: infer_dtype = pdapi.infer_dtype @@ -67,10 +69,7 @@ def read_table(self, columns=None): return table def read_pandas(self, columns=None, nthreads=None, use_threads=False): - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) return self.read_table(columns=columns).to_pandas( use_threads=use_threads) @@ -162,10 +161,7 @@ def read_pandas(self, columns=None, nthreads=None, use_threads=False): pandas.DataFrame Content of the file as a pandas DataFrame (of columns) """ - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) return self.read_table(columns=columns).to_pandas( use_threads=use_threads) @@ -213,10 +209,7 @@ def read_feather(source, columns=None, nthreads=None, use_threads=False): ------- df : pandas.DataFrame """ - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) reader = FeatherReader(source) return reader.read_pandas(columns=columns, use_threads=use_threads) diff --git a/python/pyarrow/ipc.py b/python/pyarrow/ipc.py index 4d767a37be34..bed2dd6f2fa7 100644 --- a/python/pyarrow/ipc.py +++ b/python/pyarrow/ipc.py @@ -17,8 +17,6 @@ # Arrow file and stream reader/writer classes, and other messaging tools -import warnings - import pyarrow as pa from pyarrow.lib import (Message, MessageReader, # noqa @@ -26,6 +24,7 @@ read_tensor, write_tensor, get_record_batch_size, get_tensor_size) import pyarrow.lib as lib +from .util import _deprecate_nthreads class _ReadPandasOption(object): @@ -184,10 +183,7 @@ def deserialize_pandas(buf, nthreads=None, use_threads=False): ------- df : pandas.DataFrame """ - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) buffer_reader = pa.BufferReader(buf) reader = pa.RecordBatchStreamReader(buffer_reader) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index b3cfb81359d0..960e6e86039f 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -16,7 +16,6 @@ # under the License. import json -import warnings from collections import OrderedDict @@ -28,6 +27,8 @@ except ImportError: else: import pyarrow.pandas_compat as pdcompat +from .util import _deprecate_nthreads + cdef class ChunkedArray: """ @@ -755,10 +756,7 @@ cdef class RecordBatch: ------- pandas.DataFrame """ - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) return Table.from_batches([self]).to_pandas(use_threads=use_threads) @classmethod @@ -1180,10 +1178,7 @@ cdef class Table: cdef: PandasOptions options - if nthreads is not None: - warnings.warn("`nthreads` argument is ignored, " - "pass `use_threads` instead", FutureWarning, - stacklevel=2) + use_threads = _deprecate_nthreads(use_threads, nthreads) options = PandasOptions( strings_to_categorical=strings_to_categorical, diff --git a/python/pyarrow/util.py b/python/pyarrow/util.py index b8825658d88e..2954b622355a 100644 --- a/python/pyarrow/util.py +++ b/python/pyarrow/util.py @@ -35,3 +35,13 @@ def wrapper(*args, **kwargs): warnings.warn(msg, FutureWarning) return api(*args) return wrapper + + +def _deprecate_nthreads(use_threads, nthreads): + if nthreads is not None: + warnings.warn("`nthreads` argument is deprecated, " + "pass `use_threads` instead", FutureWarning, + stacklevel=3) + if nthreads > 1: + use_threads = True + return use_threads From 934e5a11a31d2d0333633c67c0afe5bc7f8d0e92 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 12:15:11 +0200 Subject: [PATCH 11/17] Add & operator between Statuses --- cpp/src/arrow/python/arrow_to_pandas.cc | 5 +- cpp/src/arrow/status-test.cc | 37 ++++++++++++++ cpp/src/arrow/status.cc | 6 +-- cpp/src/arrow/status.h | 64 +++++++++++++++++++++++-- 4 files changed, 101 insertions(+), 11 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index 16de5cfbab1c..e4b377cd7824 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -1464,10 +1464,7 @@ class DataFrameBlockCreator { } auto final_status = Status::OK(); for (auto& fut : futures) { - Status st = fut.get(); - if (!st.ok()) { - final_status = st; - } + final_status &= fut.get(); } return final_status; } diff --git a/cpp/src/arrow/status-test.cc b/cpp/src/arrow/status-test.cc index d4f84e48ec07..b7fc61f48015 100644 --- a/cpp/src/arrow/status-test.cc +++ b/cpp/src/arrow/status-test.cc @@ -40,4 +40,41 @@ TEST(StatusTest, TestToString) { ASSERT_EQ(file_error.ToString(), ss.str()); } +TEST(StatusTest, AndStatus) { + Status a = Status::OK(); + Status b = Status::OK(); + Status c = Status::Invalid("invalid value"); + Status d = Status::IOError("file error"); + + Status res; + res = a & b; + ASSERT_TRUE(res.ok()); + res = a & c; + ASSERT_TRUE(res.IsInvalid()); + res = d & c; + ASSERT_TRUE(res.IsIOError()); + + res = Status::OK(); + res &= c; + ASSERT_TRUE(res.IsInvalid()); + res &= d; + ASSERT_TRUE(res.IsInvalid()); + + // With rvalues + res = Status::OK() & Status::Invalid("foo"); + ASSERT_TRUE(res.IsInvalid()); + res = Status::Invalid("foo") & Status::OK(); + ASSERT_TRUE(res.IsInvalid()); + res = Status::Invalid("foo") & Status::IOError("bar"); + ASSERT_TRUE(res.IsInvalid()); + + res = Status::OK(); + res &= Status::OK(); + ASSERT_TRUE(res.ok()); + res &= Status::Invalid("foo"); + ASSERT_TRUE(res.IsInvalid()); + res &= Status::IOError("bar"); + ASSERT_TRUE(res.IsInvalid()); +} + } // namespace arrow diff --git a/cpp/src/arrow/status.cc b/cpp/src/arrow/status.cc index 8d446effef7b..918dbc7d1c2a 100644 --- a/cpp/src/arrow/status.cc +++ b/cpp/src/arrow/status.cc @@ -23,12 +23,12 @@ Status::Status(StatusCode code, const std::string& msg) { state_->msg = msg; } -void Status::CopyFrom(const State* state) { +void Status::CopyFrom(const Status& s) { delete state_; - if (state == nullptr) { + if (s.state_ == nullptr) { state_ = nullptr; } else { - state_ = new State(*state); + state_ = new State(*s.state_); } } diff --git a/cpp/src/arrow/status.h b/cpp/src/arrow/status.h index 0e7f0149a073..3ba6523e3831 100644 --- a/cpp/src/arrow/status.h +++ b/cpp/src/arrow/status.h @@ -18,6 +18,7 @@ #include #include #include +#include #ifdef ARROW_EXTRA_ERROR_CONTEXT #include @@ -100,7 +101,17 @@ class ARROW_EXPORT Status { // Copy the specified status. Status(const Status& s); - void operator=(const Status& s); + Status& operator=(const Status& s); + + // Mope the specified status. + Status(Status&& s); + Status& operator=(Status&& s); + + // AND the statuses. + Status operator&(const Status& s) const; + Status operator&(Status&& s) const; + Status& operator&=(const Status& s); + Status& operator&=(Status&& s); // Return a success status. static Status OK() { return Status(); } @@ -207,7 +218,8 @@ class ARROW_EXPORT Status { // a `State` structure containing the error code and message(s) State* state_; - void CopyFrom(const State* s); + void CopyFrom(const Status& s); + void MoveFrom(Status& s); }; static inline std::ostream& operator<<(std::ostream& os, const Status& x) { @@ -215,15 +227,59 @@ static inline std::ostream& operator<<(std::ostream& os, const Status& x) { return os; } +inline void Status::MoveFrom(Status& s) { + delete state_; + state_ = s.state_; + s.state_ = NULL; +} + inline Status::Status(const Status& s) : state_((s.state_ == NULL) ? NULL : new State(*s.state_)) {} -inline void Status::operator=(const Status& s) { +inline Status& Status::operator=(const Status& s) { // The following condition catches both aliasing (when this == &s), // and the common case where both s and *this are ok. if (state_ != s.state_) { - CopyFrom(s.state_); + CopyFrom(s); + } + return *this; +} + +inline Status::Status(Status&& s) : state_(s.state_) { s.state_ = NULL; } + +inline Status& Status::operator=(Status&& s) { + MoveFrom(s); + return *this; +} + +inline Status Status::operator&(const Status& s) const { + if (ok()) { + return s; + } else { + return *this; + } +} + +inline Status Status::operator&(Status&& s) const { + if (ok()) { + return std::move(s); + } else { + return *this; + } +} + +inline Status& Status::operator&=(const Status& s) { + if (ok() && !s.ok()) { + CopyFrom(s); + } + return *this; +} + +inline Status& Status::operator&=(Status&& s) { + if (ok() && !s.ok()) { + MoveFrom(s); } + return *this; } } // namespace arrow From 2171e6e28e3144bb1b108c086e0ce0210e0718c9 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 15:17:40 +0200 Subject: [PATCH 12/17] On Windows, avoid shutting down the global thread pool at process exit --- cpp/src/arrow/status.h | 2 +- cpp/src/arrow/util/thread-pool.cc | 122 +++++++++++++++++++----------- cpp/src/arrow/util/thread-pool.h | 25 +++--- 3 files changed, 92 insertions(+), 57 deletions(-) diff --git a/cpp/src/arrow/status.h b/cpp/src/arrow/status.h index 3ba6523e3831..d1e4d66a7eac 100644 --- a/cpp/src/arrow/status.h +++ b/cpp/src/arrow/status.h @@ -103,7 +103,7 @@ class ARROW_EXPORT Status { Status(const Status& s); Status& operator=(const Status& s); - // Mope the specified status. + // Move the specified status. Status(Status&& s); Status& operator=(Status&& s); diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index 1c4fe9e1c29f..dc50ad742cb3 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -25,14 +25,39 @@ namespace arrow { namespace internal { +struct ThreadPool::State { + State() : desired_capacity_(0), please_shutdown_(false), quick_shutdown_(false) {} + + std::mutex mutex_; + std::condition_variable cv_; + std::condition_variable cv_shutdown_; + + std::list workers_; + // Trashcan for finished threads + std::vector finished_workers_; + std::deque> pending_tasks_; + + // Desired number of threads + int desired_capacity_; + // Are we shutting down? + bool please_shutdown_; + bool quick_shutdown_; +}; + ThreadPool::ThreadPool() - : desired_capacity_(0), please_shutdown_(false), quick_shutdown_(false) {} + : sp_state_(std::make_shared()), + state_(sp_state_.get()), + shutdown_on_destroy_(true) {} -ThreadPool::~ThreadPool() { ARROW_UNUSED(Shutdown(false /* wait */)); } +ThreadPool::~ThreadPool() { + if (shutdown_on_destroy_) { + ARROW_UNUSED(Shutdown(false /* wait */)); + } +} Status ThreadPool::SetCapacity(int threads) { - std::unique_lock lock(mutex_); - if (please_shutdown_) { + std::unique_lock lock(state_->mutex_); + if (state_->please_shutdown_) { return Status::Invalid("operation forbidden during or after shutdown"); } if (threads <= 0) { @@ -40,64 +65,67 @@ Status ThreadPool::SetCapacity(int threads) { } CollectFinishedWorkersUnlocked(); - desired_capacity_ = threads; - int diff = static_cast(desired_capacity_ - workers_.size()); + state_->desired_capacity_ = threads; + int diff = static_cast(threads - state_->workers_.size()); if (diff > 0) { LaunchWorkersUnlocked(diff); } else if (diff < 0) { // Wake threads to ask them to stop - cv_.notify_all(); + state_->cv_.notify_all(); } return Status::OK(); } int ThreadPool::GetCapacity() { - std::unique_lock lock(mutex_); - return desired_capacity_; + std::unique_lock lock(state_->mutex_); + return state_->desired_capacity_; } int ThreadPool::GetActualCapacity() { - std::unique_lock lock(mutex_); - return static_cast(workers_.size()); + std::unique_lock lock(state_->mutex_); + return static_cast(state_->workers_.size()); } Status ThreadPool::Shutdown(bool wait) { - std::unique_lock lock(mutex_); + std::unique_lock lock(state_->mutex_); - if (please_shutdown_) { + if (state_->please_shutdown_) { return Status::Invalid("Shutdown() already called"); } - please_shutdown_ = true; - quick_shutdown_ = !wait; - cv_.notify_all(); - cv_shutdown_.wait(lock, [this] { return workers_.empty(); }); - if (!quick_shutdown_) { - DCHECK_EQ(pending_tasks_.size(), 0); + state_->please_shutdown_ = true; + state_->quick_shutdown_ = !wait; + state_->cv_.notify_all(); + state_->cv_shutdown_.wait(lock, [this] { return state_->workers_.empty(); }); + if (!state_->quick_shutdown_) { + DCHECK_EQ(state_->pending_tasks_.size(), 0); } else { - pending_tasks_.clear(); + state_->pending_tasks_.clear(); } CollectFinishedWorkersUnlocked(); return Status::OK(); } void ThreadPool::CollectFinishedWorkersUnlocked() { - for (auto& thread : finished_workers_) { + for (auto& thread : state_->finished_workers_) { // Make sure OS thread has exited thread.join(); } - finished_workers_.clear(); + state_->finished_workers_.clear(); } void ThreadPool::LaunchWorkersUnlocked(int threads) { + std::shared_ptr state = sp_state_; + for (int i = 0; i < threads; i++) { - workers_.emplace_back(); - auto it = --workers_.end(); - *it = std::thread([this, it] { WorkerLoop(it); }); + state_->workers_.emplace_back(); + auto it = --(state_->workers_.end()); + *it = std::thread([state, it] { WorkerLoop(state, it); }); } } -void ThreadPool::WorkerLoop(std::list::iterator it) { - std::unique_lock lock(mutex_); +void ThreadPool::WorkerLoop(std::shared_ptr state, + std::list::iterator it) { + std::unique_lock lock(state->mutex_); // Since we hold the lock, `it` now points to the correct thread object // (LaunchWorkersUnlocked has exited) @@ -109,27 +137,28 @@ void ThreadPool::WorkerLoop(std::list::iterator it) { // condition variable at the end of the loop. // Execute pending tasks if any - while (!pending_tasks_.empty() && !quick_shutdown_) { + while (!state->pending_tasks_.empty() && !state->quick_shutdown_) { // If too many threads, secede from the pool. // We check this opportunistically at each loop iteration since // it releases the lock below. - if (workers_.size() > static_cast(desired_capacity_)) { + if (state->workers_.size() > static_cast(state->desired_capacity_)) { break; } { - std::function task = std::move(pending_tasks_.front()); - pending_tasks_.pop_front(); + std::function task = std::move(state->pending_tasks_.front()); + state->pending_tasks_.pop_front(); lock.unlock(); task(); } lock.lock(); } // Now either the queue is empty *or* a quick shutdown was requested - if (please_shutdown_ || workers_.size() > static_cast(desired_capacity_)) { + if (state->please_shutdown_ || + state->workers_.size() > static_cast(state->desired_capacity_)) { break; } // Wait for next wakeup - cv_.wait(lock); + state->cv_.wait(lock); } // We're done. Move our thread object to the trashcan of finished @@ -140,24 +169,24 @@ void ThreadPool::WorkerLoop(std::list::iterator it) { // are exited before the ThreadPool is destroyed. Otherwise subtle // timing conditions can lead to false positives with Valgrind. DCHECK_EQ(std::this_thread::get_id(), it->get_id()); - finished_workers_.push_back(std::move(*it)); - workers_.erase(it); - if (please_shutdown_) { + state->finished_workers_.push_back(std::move(*it)); + state->workers_.erase(it); + if (state->please_shutdown_) { // Notify the function waiting in Shutdown(). - cv_shutdown_.notify_one(); + state->cv_shutdown_.notify_one(); } } Status ThreadPool::SpawnReal(std::function task) { { - std::lock_guard lock(mutex_); - if (please_shutdown_) { + std::lock_guard lock(state_->mutex_); + if (state_->please_shutdown_) { return Status::Invalid("operation forbidden during or after shutdown"); } CollectFinishedWorkersUnlocked(); - pending_tasks_.push_back(std::move(task)); + state_->pending_tasks_.push_back(std::move(task)); } - cv_.notify_one(); + state_->cv_.notify_one(); return Status::OK(); } @@ -208,14 +237,21 @@ int ThreadPool::DefaultCapacity() { } // Helper for the singleton pattern -static std::shared_ptr MakePoolWithDefaultCapacity() { +std::shared_ptr ThreadPool::MakeCpuThreadPool() { std::shared_ptr pool; DCHECK_OK(ThreadPool::Make(ThreadPool::DefaultCapacity(), &pool)); + // On Windows, the global 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. +#ifdef _WIN32 + pool->shutdown_on_destroy_ = false; +#endif return pool; } ThreadPool* GetCpuThreadPool() { - static std::shared_ptr singleton = MakePoolWithDefaultCapacity(); + static std::shared_ptr singleton = ThreadPool::MakeCpuThreadPool(); return singleton.get(); } diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index a7f3d6452121..d547c7ffcbc3 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -125,6 +125,9 @@ class ARROW_EXPORT ThreadPool { protected: FRIEND_TEST(TestThreadPool, SetCapacity); FRIEND_TEST(TestGlobalThreadPool, Capacity); + friend ARROW_EXPORT ThreadPool* GetCpuThreadPool(); + + struct State; ThreadPool(); @@ -135,23 +138,19 @@ class ARROW_EXPORT ThreadPool { void CollectFinishedWorkersUnlocked(); // Launch a given number of additional workers void LaunchWorkersUnlocked(int threads); - void WorkerLoop(std::list::iterator it); + // Get the current actual capacity int GetActualCapacity(); - std::mutex mutex_; - std::condition_variable cv_; - std::condition_variable cv_shutdown_; + // The worker loop is a static method so that it can keep running + // after the ThreadPool is destroyed + static void WorkerLoop(std::shared_ptr state, + std::list::iterator it); - std::list workers_; - // Trashcan for finished threads - std::vector finished_workers_; - std::deque> pending_tasks_; + static std::shared_ptr MakeCpuThreadPool(); - // Desired number of threads - int desired_capacity_; - // Are we shutting down? - bool please_shutdown_; - bool quick_shutdown_; + std::shared_ptr sp_state_; + State* state_; + bool shutdown_on_destroy_; }; // Return the process-global thread pool for CPU-bound tasks. From d0a527ababfb6f62230b5e95267bcdf98255a5b5 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 15:39:02 +0200 Subject: [PATCH 13/17] Restore single-thread path in WriteTableToBlocks() --- cpp/src/arrow/python/arrow_to_pandas.cc | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index e4b377cd7824..79b47fc7dce2 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -1457,16 +1457,23 @@ class DataFrameBlockCreator { return block->Write(this->table_->column(i), i, this->column_block_placement_[i]); }; - arrow::internal::ThreadPool* pool = arrow::internal::GetCpuThreadPool(); - std::vector> futures; - for (int i = 0; i < table_->num_columns(); ++i) { - futures.push_back(pool->Submit(WriteColumn, i)); - } - auto final_status = Status::OK(); - for (auto& fut : futures) { - final_status &= fut.get(); + if (use_threads) { + arrow::internal::ThreadPool* pool = arrow::internal::GetCpuThreadPool(); + std::vector> futures; + for (int i = 0; i < table_->num_columns(); ++i) { + futures.push_back(pool->Submit(WriteColumn, i)); + } + auto final_status = Status::OK(); + for (auto& fut : futures) { + final_status &= fut.get(); + } + return final_status; + } else { + for (int i = 0; i < table_->num_columns(); ++i) { + RETURN_NOT_OK(WriteColumn(i)); + } + return Status::OK(); } - return final_status; } Status AppendBlocks(const BlockMap& blocks, PyObject* list) { From 4567a2c3e32bd86458b5a73019da7657135fd17c Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 16:08:46 +0200 Subject: [PATCH 14/17] Add a two-argument variant of ParallelFor() that uses the global CPU thread pool --- cpp/src/arrow/python/arrow_to_pandas.cc | 13 ++----------- cpp/src/arrow/util/parallel.h | 25 +++++++++++++++++++++---- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index 79b47fc7dce2..d37463a165f4 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -40,7 +40,7 @@ #include "arrow/util/decimal.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" -#include "arrow/util/thread-pool.h" +#include "arrow/util/parallel.h" #include "arrow/visitor_inline.h" #include "arrow/compute/api.h" @@ -1458,16 +1458,7 @@ class DataFrameBlockCreator { }; if (use_threads) { - arrow::internal::ThreadPool* pool = arrow::internal::GetCpuThreadPool(); - std::vector> futures; - for (int i = 0; i < table_->num_columns(); ++i) { - futures.push_back(pool->Submit(WriteColumn, i)); - } - auto final_status = Status::OK(); - for (auto& fut : futures) { - final_status &= fut.get(); - } - return final_status; + return ParallelFor(table_->num_columns(), WriteColumn); } else { for (int i = 0; i < table_->num_columns(); ++i) { RETURN_NOT_OK(WriteColumn(i)); diff --git a/cpp/src/arrow/util/parallel.h b/cpp/src/arrow/util/parallel.h index e151cafc849b..156679e2e4c9 100644 --- a/cpp/src/arrow/util/parallel.h +++ b/cpp/src/arrow/util/parallel.h @@ -24,14 +24,31 @@ #include #include "arrow/status.h" +#include "arrow/util/thread-pool.h" namespace arrow { // A parallelizer that takes a `Status(int)` function and calls it with -// arguments between 0 and `num_tasks - 1`, using the given number of -// concurrent threads. -// In most cases it's more appropriate to use the global CPU thread pool -// (see arrow/util/thread-pool.h) +// arguments between 0 and `num_tasks - 1`, on an arbitrary number of threads. + +template +Status ParallelFor(int num_tasks, FUNCTION&& func) { + auto pool = internal::GetCpuThreadPool(); + std::vector> futures(num_tasks); + + for (int i = 0; i < num_tasks; ++i) { + futures[i] = pool->Submit(func, i); + } + auto st = Status::OK(); + for (auto& fut : futures) { + st &= fut.get(); + } + return st; +} + +// A variant of ParallelFor() with an explicit number of dedicated threads. +// In most cases it's more appropriate to use the 2-argument ParallelFor (above), +// or directly the global CPU thread pool (arrow/util/thread-pool.h). template Status ParallelFor(int nthreads, int num_tasks, FUNCTION&& func) { From f601d4e9fb9af566691cb8d3f229cd635d7e2e09 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 16:15:31 +0200 Subject: [PATCH 15/17] ThreadPool::State pointer is const --- cpp/src/arrow/util/thread-pool.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool.h b/cpp/src/arrow/util/thread-pool.h index d547c7ffcbc3..c1b10f7d003c 100644 --- a/cpp/src/arrow/util/thread-pool.h +++ b/cpp/src/arrow/util/thread-pool.h @@ -148,8 +148,8 @@ class ARROW_EXPORT ThreadPool { static std::shared_ptr MakeCpuThreadPool(); - std::shared_ptr sp_state_; - State* state_; + const std::shared_ptr sp_state_; + State* const state_; bool shutdown_on_destroy_; }; From a7aeed0e033143f87c476dac63e98ef67c4a2349 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 16:19:35 +0200 Subject: [PATCH 16/17] Factor out secession predicate --- cpp/src/arrow/util/thread-pool.cc | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/cpp/src/arrow/util/thread-pool.cc b/cpp/src/arrow/util/thread-pool.cc index dc50ad742cb3..997ff5d743e1 100644 --- a/cpp/src/arrow/util/thread-pool.cc +++ b/cpp/src/arrow/util/thread-pool.cc @@ -131,6 +131,11 @@ void ThreadPool::WorkerLoop(std::shared_ptr state, // (LaunchWorkersUnlocked has exited) DCHECK_EQ(std::this_thread::get_id(), it->get_id()); + // If too many threads, we should secede from the pool + const auto should_secede = [&]() -> bool { + return state->workers_.size() > static_cast(state->desired_capacity_); + }; + while (true) { // By the time this thread is started, some tasks may have been pushed // or shutdown could even have been requested. So we only wait on the @@ -138,10 +143,9 @@ void ThreadPool::WorkerLoop(std::shared_ptr state, // Execute pending tasks if any while (!state->pending_tasks_.empty() && !state->quick_shutdown_) { - // If too many threads, secede from the pool. // We check this opportunistically at each loop iteration since // it releases the lock below. - if (state->workers_.size() > static_cast(state->desired_capacity_)) { + if (should_secede()) { break; } { @@ -153,8 +157,7 @@ void ThreadPool::WorkerLoop(std::shared_ptr state, lock.lock(); } // Now either the queue is empty *or* a quick shutdown was requested - if (state->please_shutdown_ || - state->workers_.size() > static_cast(state->desired_capacity_)) { + if (state->please_shutdown_ || should_secede()) { break; } // Wait for next wakeup From 91187bf640ae5337f0454a69b0b47c7c2fe37381 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 24 May 2018 17:24:51 +0200 Subject: [PATCH 17/17] Move use_threads flag into PandasOptions --- cpp/src/arrow/python/arrow_to_pandas.cc | 20 ++++++++++---------- cpp/src/arrow/python/arrow_to_pandas.h | 10 ++++++---- cpp/src/arrow/python/python-test.cc | 4 ++-- python/pyarrow/array.pxi | 3 ++- python/pyarrow/includes/libarrow.pxd | 3 ++- python/pyarrow/pandas_compat.py | 13 +++++-------- python/pyarrow/table.pxi | 14 +++++++------- 7 files changed, 34 insertions(+), 33 deletions(-) diff --git a/cpp/src/arrow/python/arrow_to_pandas.cc b/cpp/src/arrow/python/arrow_to_pandas.cc index d37463a165f4..71b62cf8689f 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.cc +++ b/cpp/src/arrow/python/arrow_to_pandas.cc @@ -1370,14 +1370,14 @@ class DataFrameBlockCreator { const std::shared_ptr
& table, MemoryPool* pool) : table_(table), options_(options), pool_(pool) {} - Status Convert(bool use_threads, PyObject** output) { + Status Convert(PyObject** output) { column_types_.resize(table_->num_columns()); column_block_placement_.resize(table_->num_columns()); type_counts_.clear(); blocks_.clear(); RETURN_NOT_OK(CreateBlocks()); - RETURN_NOT_OK(WriteTableToBlocks(use_threads)); + RETURN_NOT_OK(WriteTableToBlocks()); return GetResultList(output); } @@ -1450,14 +1450,14 @@ class DataFrameBlockCreator { return Status::OK(); } - Status WriteTableToBlocks(bool use_threads) { + Status WriteTableToBlocks() { auto WriteColumn = [this](int i) { std::shared_ptr block; RETURN_NOT_OK(this->GetBlock(i, &block)); return block->Write(this->table_->column(i), i, this->column_block_placement_[i]); }; - if (use_threads) { + if (options_.use_threads) { return ParallelFor(table_->num_columns(), WriteColumn); } else { for (int i = 0; i < table_->num_columns(); ++i) { @@ -1864,15 +1864,15 @@ Status ConvertColumnToPandas(PandasOptions options, const std::shared_ptr& table, - bool use_threads, MemoryPool* pool, PyObject** out) { - return ConvertTableToPandas(options, std::unordered_set(), table, - use_threads, pool, out); + MemoryPool* pool, PyObject** out) { + return ConvertTableToPandas(options, std::unordered_set(), table, pool, + out); } Status ConvertTableToPandas(PandasOptions options, const std::unordered_set& categorical_columns, - const std::shared_ptr
& table, bool use_threads, - MemoryPool* pool, PyObject** out) { + const std::shared_ptr
& table, MemoryPool* pool, + PyObject** out) { std::shared_ptr
current_table = table; if (!categorical_columns.empty()) { FunctionContext ctx; @@ -1892,7 +1892,7 @@ Status ConvertTableToPandas(PandasOptions options, } DataFrameBlockCreator helper(options, current_table, pool); - return helper.Convert(use_threads, out); + return helper.Convert(out); } } // namespace py diff --git a/cpp/src/arrow/python/arrow_to_pandas.h b/cpp/src/arrow/python/arrow_to_pandas.h index ead6cd8c0946..2d322813b771 100644 --- a/cpp/src/arrow/python/arrow_to_pandas.h +++ b/cpp/src/arrow/python/arrow_to_pandas.h @@ -45,11 +45,13 @@ struct PandasOptions { bool strings_to_categorical; bool zero_copy_only; bool integer_object_nulls; + bool use_threads; PandasOptions() : strings_to_categorical(false), zero_copy_only(false), - integer_object_nulls(false) {} + integer_object_nulls(false), + use_threads(false) {} }; ARROW_EXPORT @@ -68,7 +70,7 @@ Status ConvertColumnToPandas(PandasOptions options, const std::shared_ptr& table, - bool use_threads, MemoryPool* pool, PyObject** out); + MemoryPool* pool, PyObject** out); /// Convert a whole table as efficiently as possible to a pandas.DataFrame. /// @@ -77,8 +79,8 @@ Status ConvertTableToPandas(PandasOptions options, const std::shared_ptr
& ARROW_EXPORT Status ConvertTableToPandas(PandasOptions options, const std::unordered_set& categorical_columns, - const std::shared_ptr
& table, bool use_threads, - MemoryPool* pool, PyObject** out); + const std::shared_ptr
& table, MemoryPool* pool, + PyObject** out); } // namespace py } // namespace arrow diff --git a/cpp/src/arrow/python/python-test.cc b/cpp/src/arrow/python/python-test.cc index cbab897c4337..abe93b04f98f 100644 --- a/cpp/src/arrow/python/python-test.cc +++ b/cpp/src/arrow/python/python-test.cc @@ -238,9 +238,9 @@ TEST(PandasConversionTest, TestObjectBlockWriteFails) { PyObject* out; Py_BEGIN_ALLOW_THREADS; PandasOptions options; + options.use_threads = true; MemoryPool* pool = default_memory_pool(); - ASSERT_RAISES(UnknownError, - ConvertTableToPandas(options, table, true /* use_threads */, pool, &out)); + ASSERT_RAISES(UnknownError, ConvertTableToPandas(options, table, pool, &out)); Py_END_ALLOW_THREADS; } diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 94c37b35616d..3f84f1783024 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -602,7 +602,8 @@ cdef class Array: options = PandasOptions( strings_to_categorical=strings_to_categorical, zero_copy_only=zero_copy_only, - integer_object_nulls=integer_object_nulls) + integer_object_nulls=integer_object_nulls, + use_threads=False) with nogil: check_status(ConvertArrayToPandas(options, self.sp_array, self, &out)) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 586f27885676..5b0c2119831b 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -959,7 +959,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: PandasOptions options, const unordered_set[c_string]& categorical_columns, const shared_ptr[CTable]& table, - c_bool use_threads, CMemoryPool* pool, + CMemoryPool* pool, PyObject** out) void c_set_default_memory_pool \ @@ -987,6 +987,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: c_bool strings_to_categorical c_bool zero_copy_only c_bool integer_object_nulls + c_bool use_threads cdef extern from "arrow/python/api.h" namespace 'arrow::py' nogil: diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index 63907b830e28..18d8ed3d356c 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -493,8 +493,7 @@ def _make_datetimetz(tz): # Converting pyarrow.Table efficiently to pandas.DataFrame -def table_to_blockmanager(options, table, memory_pool, use_threads, - categories=None): +def table_to_blockmanager(options, table, memory_pool, categories=None): from pyarrow.compat import DatetimeTZDtype index_columns = [] @@ -568,8 +567,7 @@ def table_to_blockmanager(options, table, memory_pool, use_threads, block_table.schema.get_field_index(raw_name) ) - blocks = _table_to_blocks(options, block_table, use_threads, memory_pool, - categories) + blocks = _table_to_blocks(options, block_table, memory_pool, categories) # Construct the row index if len(index_arrays) > 1: @@ -728,13 +726,12 @@ def _reconstruct_columns_from_metadata(columns, column_indexes): return pd.MultiIndex(levels=new_levels, labels=labels, names=columns.names) -def _table_to_blocks(options, block_table, use_threads, memory_pool, - categories): +def _table_to_blocks(options, block_table, memory_pool, categories): # Part of table_to_blockmanager # Convert an arrow table to Block from the internal pandas API - result = pa.lib.table_to_blocks(options, block_table, use_threads, - memory_pool, categories) + result = pa.lib.table_to_blocks(options, block_table, memory_pool, + categories) # Defined above return [_reconstruct_block(item) for item in result] diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 960e6e86039f..4edf5af4a237 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -367,7 +367,8 @@ cdef class Column: options = PandasOptions( strings_to_categorical=strings_to_categorical, zero_copy_only=zero_copy_only, - integer_object_nulls=integer_object_nulls) + integer_object_nulls=integer_object_nulls, + use_threads=False) with nogil: check_status(libarrow.ConvertColumnToPandas(options, @@ -828,7 +829,7 @@ cdef class RecordBatch: CRecordBatch.Make(schema, num_rows, c_arrays)) -def table_to_blocks(PandasOptions options, Table table, c_bool use_threads, +def table_to_blocks(PandasOptions options, Table table, MemoryPool memory_pool, categories): cdef: PyObject* result_obj @@ -843,9 +844,7 @@ def table_to_blocks(PandasOptions options, Table table, c_bool use_threads, with nogil: check_status( libarrow.ConvertTableToPandas( - options, categorical_columns, c_table, use_threads, pool, - &result_obj - ) + options, categorical_columns, c_table, pool, &result_obj) ) return PyObject_to_object(result_obj) @@ -1183,10 +1182,11 @@ cdef class Table: options = PandasOptions( strings_to_categorical=strings_to_categorical, zero_copy_only=zero_copy_only, - integer_object_nulls=integer_object_nulls) + integer_object_nulls=integer_object_nulls, + use_threads=use_threads) self._check_nullptr() mgr = pdcompat.table_to_blockmanager(options, self, memory_pool, - use_threads, categories) + categories) return pd.DataFrame(mgr) def to_pydict(self):