Crates.io | orx-concurrent-bag |
lib.rs | orx-concurrent-bag |
version | 2.7.0 |
source | src |
created_at | 2024-03-10 19:46:19.053315 |
updated_at | 2024-09-06 13:32:41.726893 |
description | An efficient, convenient and lightweight grow-only concurrent data structure allowing high performance concurrent collection. |
homepage | |
repository | https://github.com/orxfun/orx-concurrent-bag/ |
max_upload_size | |
id | 1168890 |
size | 217,948 |
An efficient, convenient and lightweight grow-only concurrent data structure allowing high performance concurrent collection.
ConcurrentBag
can safely be shared among threads simply as a shared reference. It is a PinnedConcurrentCol
with a special concurrent state implementation. Underlying PinnedVec
and concurrent bag can be converted back and forth to each other.ConcurrentBag
is a lock free structure suitable for concurrent, copy-free and high performance growth. You may see benchmarks and further performance notes for details.Underlying PinnedVec
guarantees make it straightforward to safely grow with a shared reference which leads to a convenient api as demonstrated below.
use orx_concurrent_bag::*;
let bag = ConcurrentBag::new();
let (num_threads, num_items_per_thread) = (4, 1_024);
let bag_ref = &bag;
std::thread::scope(|s| {
for i in 0..num_threads {
s.spawn(move || {
for j in 0..num_items_per_thread {
// concurrently collect results simply by calling `push`
bag_ref.push(i * 1000 + j);
}
});
}
});
let mut vec_from_bag = bag.into_inner().to_vec();
vec_from_bag.sort();
let mut expected: Vec<_> = (0..num_threads).flat_map(|i| (0..num_items_per_thread).map(move |j| i * 1000 + j)).collect();
expected.sort();
assert_eq!(vec_from_bag, expected);
The concurrent state is modeled simply by an atomic length. Combination of this state and PinnedConcurrentCol
leads to the following properties:
into_inner(self)
.PinnedVec
.push
You may find the details of the benchmarks at benches/collect_with_push.rs.
In the experiment, rayon
s parallel iterator, and push methods of AppendOnlyVec
, boxcar::Vec
and ConcurrentBag
are used to collect results from multiple threads. Further, different underlying pinned vectors of the ConcurrentBag
are evaluated.
// reserve and push one position at a time
for j in 0..num_items_per_thread {
bag.push(i * 1000 + j);
}
We observe that ConcurrentBag
allows for a highly efficient concurrent collection of elements:
Doubling
growth strategy of the concurrent bag, which is the most flexible as it does not require any prior knowledge, already seems to outperform the alternatives. Hence, it can be used in most situations.Linear
growth strategy requires one argument determining the uniform fragment capacity of the underlying SplitVec
. This strategy might be preferred whenever we would like to be more conservative about allocation. Recall that capacity of Doubling
, similar to the standard Vec, grows exponentially; while as the name suggests Linear
grows linearly.Fixed
growth strategy is the least flexible and requires perfect knowledge about the hard-constrained capacity (will panic if we exceed). Since it does not outperform Doubling
or Linear
, we do not necessarily required to use Fixed
except for the rare cases where we want to allocate exactly the required memory that we know beforehand.The performance can further be improved by using extend
method instead of push
. You may see results in the next subsection and details in the performance notes.
extend
You may find the details of the benchmarks at benches/collect_with_extend.rs.
The only difference in this follow up experiment is that we use extend
rather than push
with ConcurrentBag
. The expectation is that this approach will solve the performance degradation due to false sharing in the small data & little work situation.
In a perfectly homogeneous scenario, we can evenly share the work to threads as follows.
// reserve num_items_per_thread positions at a time
// and then push as the iterator yields
let iter = (0..num_items_per_thread).map(|j| i * 100000 + j);
bag.extend(iter);
However, we do not need to have perfect homogeneity or perfect information on the number of items to be pushed per thread to get the benefits of extend
. We can simply step_by
and extend by batch_size
elements. A large enough batch_size
so that batch size elements exceed a cache line would be sufficient to prevent the dramatic performance degradation of false sharing.
// reserve batch_size positions at each iteration
// and then push as the iterator yields
for j in (0..num_items_per_thread).step_by(batch_size) {
let iter = (j..(j + batch_size)).map(|j| i * 100000 + j);
bag.extend(iter);
}
Although concurrent collection via ConcurrentBag::push
is highly efficient, collection with ConcurrentBag::extend
certainly needs to be considered whenever possible as it changes the scale. As the graph below demonstrates, collection in batches of only 64 elements while collecting tens of thousands of elements provides orders of magnitudes of improvement.
ConcurrentBag |
ConcurrentVec |
ConcurrentOrderedBag |
|
---|---|---|---|
Write | Guarantees that each element is written exactly once via push or extend methods |
Guarantees that each element is written exactly once via push or extend methods |
Different in two ways. First, a position can be written multiple times. Second, an arbitrary element of the bag can be written at any time at any order using set_value and set_values methods. This provides a great flexibility while moving the safety responsibility to the caller; hence, the set methods are unsafe . |
Read | Mainly, a write-only collection. Concurrent reading of already pushed elements is through unsafe get and iter methods. The caller is required to avoid race conditions. |
A write-and-read collection. Already pushed elements can safely be read through get and iter methods. |
Not supported currently. Due to the flexible but unsafe nature of write operations, it is difficult to provide required safety guarantees as a caller. |
Ordering of Elements | Since write operations are through adding elements to the end of the pinned vector via push and extend , two multi-threaded executions of a code that collects elements into the bag might result in the elements being collected in different orders. |
Since write operations are through adding elements to the end of the pinned vector via push and extend , two multi-threaded executions of a code that collects elements into the bag might result in the elements being collected in different orders. |
This is the main goal of this collection, allowing to collect elements concurrently and in the correct order. Although this does not seem trivial; it can be achieved almost trivially when ConcurrentOrderedBag is used together with a ConcurrentIter . |
into_inner |
Once the concurrent collection is completed, the bag can safely and cheaply be converted to its underlying PinnedVec<T> . |
Once the concurrent collection is completed, the vec can safely be converted to its underlying PinnedVec<ConcurrentOption<T>> . Notice that elements are wrapped with a ConcurrentOption in order to provide thread safe concurrent read & write operations. |
Growing through flexible setters allowing to write to any position, ConcurrentOrderedBag has the risk of containing gaps. into_inner call provides some useful metrics such as whether the number of elements pushed elements match the maximum index of the vector; however, it cannot guarantee that the bag is gap-free. The caller is required to take responsibility to unwrap to get the underlying PinnedVec<T> through an unsafe call. |
There is only one waiting or spinning condition of the push and extend methods: whenever the underlying PinnedVec
needs to grow. Note that growth with pinned vector is copy free. Therefore, when it spins, all it waits for is the allocation. Since number of growth is deterministic, so is the number of spins.
For instance, assume that we will push a total of 15_000 elements concurrently to an empty bag.
SplitVec<_, Doubling>
as the underlying pinned vector. Throughout the execution, we will allocate fragments of capacities [4, 8, 16, ..., 4096, 8192] which will lead to a total capacity of 16_380. In other words, we will allocate exactly 12 times during the entire execution.SplitVec<_, Linear>
with constant fragment lengths of 1_024, we will allocate 15 equal capacity fragments.FixedVec<_>
, we have to pre-allocate a safe amount and can never grow beyond this number. Therefore, there will never be any spinning.We need to be aware of the potential false sharing risk which might lead to significant performance degradation when we are filling the bag with one by one with [ConcurrentBag::push
].
Performance degradation due to false sharing might be observed specifically when both of the following conditions hold:
push
calls.The example above fits this situation. Each thread only performs one multiplication and addition in between pushing elements, and the elements to be pushed are small.
ConcurrentBag
assigns unique positions to each value to be pushed. There is no true sharing among threads in the position level.extend
to Avoid False SharingAssume that we are filling a ConcurrentBag
from n threads. At any given point, thread A calls extend
by passing in an iterator which will yield 64 elements. Concurrent bag will reserve 64 consecutive positions for this extend call. Concurrent push or extend calls from other threads will not have access to these positions. Assuming that size of 64 elements is large enough:
Required change in the code from push
to extend
is not significant. The example above could be revised as follows to avoid the performance degrading of false sharing.
use orx_concurrent_bag::*;
let (num_threads, num_items_per_thread) = (4, 1_024);
let bag = ConcurrentBag::new();
let batch_size = 64;
let bag_ref = &bag;
std::thread::scope(|s| {
for i in 0..num_threads {
s.spawn(move || {
for j in (0..num_items_per_thread).step_by(batch_size) {
let iter = (j..(j + batch_size)).map(|j| i * 1000 + j);
bag_ref.extend(iter);
}
});
}
});
Contributions are welcome! If you notice an error, have a question or think something could be improved, please open an issue or create a PR.
This library is licensed under MIT license. See LICENSE for details.