# thread safe data sharing

A computing technique for safely sharing data between threads using isolation, immutability, atomic operations, messaging, thread-safe data structures, or locks.

This is one page of public article previews, not the complete archive. Follow Next page to continue. Summaries are not the original full articles.

## Traffic mix matters

DevFeed: [Traffic mix matters](<https://devfeed.tech/articles/traffic-mix-matters-140983.md>)

Original publisher: [Read original article](<http://brooker.co.za/blog/2026/11/18/workload-mix.html>)

Author: Marc Brooker

Published: 2026-11-18T00:00:00Z

Content type: article

Language: en

Sources: [Marc Brooker's](<https://devfeed.tech/sources/marc-brooker-s-blog.md>)

Topics: [Benchmark](<https://devfeed.tech/topics/benchmark.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [CPU Cache](<https://devfeed.tech/topics/cpu-cache.md>)

Tags: [cache](<https://devfeed.tech/tags/cache.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [database](<https://devfeed.tech/tags/database.md>), [distribution](<https://devfeed.tech/tags/distribution.md>), [fast](<https://devfeed.tech/tags/fast.md>), [fifo](<https://devfeed.tech/tags/fifo.md>), [limit](<https://devfeed.tech/tags/limit.md>), [load](<https://devfeed.tech/tags/load.md>), [load-testing](<https://devfeed.tech/tags/load-testing.md>), [local](<https://devfeed.tech/tags/local.md>), [lock](<https://devfeed.tech/tags/lock.md>), [locks](<https://devfeed.tech/tags/locks.md>), [m365](<https://devfeed.tech/tags/m365.md>), [memory](<https://devfeed.tech/tags/memory.md>), [model](<https://devfeed.tech/tags/model.md>), [postgres](<https://devfeed.tech/tags/postgres.md>), [queue](<https://devfeed.tech/tags/queue.md>), [store](<https://devfeed.tech/tags/store.md>), [system](<https://devfeed.tech/tags/system.md>), [traffic](<https://devfeed.tech/tags/traffic.md>)

### AI overview

Workload mix can change throughput by orders of magnitude, so load tests and benchmarks need traffic that resembles production. In a 16-worker lock-table simulation, keys follow a Zipf distribution: greater skew concentrates contention on a few locks, lowering throughput and leaving other resources underused. In a second model, requests use an LRU cache backed by slower storage; greater skew improves cache hits and throughput across a broad range. The opposing results show that key skew can affect systems in different ways. The excerpt also notes a preference for optimistic concurrency control and a single cost/latency mode, and says Aurora DSQL sends reads to one fast storage layer without workers waiting on locks.

### Source excerpt

Traffic mix matters Wanna listen to my mixtape? The preliminary report on last week's M365 outage contains one statement that really caught my eye: Our normal load testing did not detect the latent issue because [of] the traffic mix and SKUs used in our labs. There's a lot going on in this report (as there is in any report for a complex system), but I wanted to zoom in on this one issue: traffic mix. It's important, because its the one thing that makes the difference between a great load test and a complete waste of time. The performance of computer systems is extremely sensitive to workload mix. Let's start with a simple simulator, looking at a system with a table of locks. Requests arrive with a key, hold the lock for their key for some period of time, and then free the lock and complete. This isn't an unreasonable mental model of a relational database, where each transaction takes a lock during its execution. arrivals backlog 16 worker threads lock table (one lock per key) done Poisson FIFO, never empty at saturation holder FIFO waiters hold ~Exp(mean 1 ms) key 1 key 2 key 3 ⋮ key N holding its key's lock blocked behind the holder (thread still occupied) Keys (N): Simulate Each request takes one of 16 worker threads, waits in a FIFO queue for the lock on its key, holds the lock for an exponentially distributed time (mean 1 ms), then releases it and frees its thread. Keys are drawn from a Zipf distribution over N keys; a coefficient of 0 is uniform. As we may expect, the more skewed the distribution, the less throughput you get out of the system. A small number of keys are highly contended, leading to under utilization of the rest of the resources of the machine, driven by the global concurrency limit. Now, let's consider a different mental model of a relational database (at least a single-system one like Postgres). A fast, local, in-memory cache containing some of the accessed data backed by a slower store containing the rest of the data. arrivals backlog 16 work

## MTRDMA: Lightweight User-Space Control-Plane Isolation for Multi-Tenant RDMA

DevFeed: [MTRDMA: Lightweight User-Space Control-Plane Isolation for Multi-Tenant RDMA](<https://devfeed.tech/articles/mtrdma-lightweight-user-space-control-plane-isolation-for-multi-tenant-rdma-126800.md>)

Original publisher: [Read original article](<https://arxiv.org/abs/2611.11991>)

Author: Hongyu Wang, Peihao Huang, Bangbo Liang, Lei Wang, Guo Chen

Published: 2026-11-10T05:00:00Z

Content type: article

Language: en

Sources: [arXiv: Networking](<https://devfeed.tech/sources/arxiv-networking.md>)

Topics: [control-plane](<https://devfeed.tech/topics/control-plane.md>), [rdma](<https://devfeed.tech/topics/rdma.md>), [cgroups](<https://devfeed.tech/topics/cgroups.md>), [Process](<https://devfeed.tech/topics/process.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>)

Tags: [atomic](<https://devfeed.tech/tags/atomic.md>), [cache](<https://devfeed.tech/tags/cache.md>), [cgroup](<https://devfeed.tech/tags/cgroup.md>), [collector](<https://devfeed.tech/tags/collector.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [containers](<https://devfeed.tech/tags/containers.md>), [control-plane](<https://devfeed.tech/tags/control-plane.md>), [cs-ni](<https://devfeed.tech/tags/cs-ni.md>), [isolation](<https://devfeed.tech/tags/isolation.md>), [ledger](<https://devfeed.tech/tags/ledger.md>), [lightweight](<https://devfeed.tech/tags/lightweight.md>), [networking](<https://devfeed.tech/tags/networking.md>), [overhead](<https://devfeed.tech/tags/overhead.md>), [pair](<https://devfeed.tech/tags/pair.md>), [quota](<https://devfeed.tech/tags/quota.md>), [rdma](<https://devfeed.tech/tags/rdma.md>), [region](<https://devfeed.tech/tags/region.md>), [user](<https://devfeed.tech/tags/user.md>), [zero-copy](<https://devfeed.tech/tags/zero-copy.md>)

### AI overview

MTRDMA isolates RDMA control-plane resources on commodity RNICs to prevent one tenant's activity from degrading others. It intercepts library-level control-plane operations and enforces hierarchical quotas while preserving the zero-copy data path. Its mechanisms include atomic shared-memory quota state with per-process cached admission (~0.13 μs), a hybrid collector that reclaims orphaned quota within seconds, and rdma-cgroup caps with ledger-kernel reconciliation to bound and detect residual tampering. On ConnectX-6, it reduced victim degradation under Queue Pair cache exhaustion from 94.5% to 0.08%, also protected against Memory Region cache exhaustion, and supported 256 concurrent tenants with negligible data-plane overhead.

### Source excerpt

arXiv:2611.11991v1 Announce Type: new Abstract: In managed multi-tenant clouds, RDMA's lack of control-plane (CP) resource isolation lets a noisy tenant exhaust shared NIC microarchitectural caches, degrading victim throughput by up to 96.4\%. Data-path schedulers leave CP resources unprotected, and hardware approaches require FPGAs or SmartNICs rather than the commodity RNICs operators already deploy. We present MTRDMA, a lightweight user-space CP isolation mechanism for commodity RNICs, applicable to managed runtimes such as containers and sandboxed processes. MTRDMA intercepts library-level CP operations to enforce hierarchical quotas while preserving the zero-copy data path, using atomic shared-memory quota state with per-process cached admission (${\sim}$0.13\,$\mu$s), a hybrid garbage collector that reclaims orphaned quota within seconds, and rdma-cgroup caps with ledger--kernel reconciliation to bound and detect residual tampering. On ConnectX-6 RNICs, MTRDMA cuts victim degradation under Queue Pair (QP) cache exhaustion from 94.5\% to 0.08\%, extends protection to Memory Region (MR) cache exhaustion, and scales to 256 concurrent tenants with negligible data-plane overhead.

## Understanding Lazy thread safety modes

DevFeed: [Understanding Lazy thread safety modes](<https://devfeed.tech/articles/understanding-lazy-thread-safety-modes-116292.md>)

Original publisher: [Read original article](<https://andrewlock.net/understanding-lazy-thread-safety-modes/>)

Author: Andrew Lock

Published: 2026-11-03T10:00:00Z

Content type: article

Language: en

Sources: [Andrew Lock | .NET Escapades](<https://devfeed.tech/sources/andrew-lock-net-escapades.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Exception](<https://devfeed.tech/topics/exception.md>), [locking](<https://devfeed.tech/topics/locking.md>)

Tags: [caching](<https://devfeed.tech/tags/caching.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [exceptions](<https://devfeed.tech/tags/exceptions.md>), [lazy](<https://devfeed.tech/tags/lazy.md>), [net-core](<https://devfeed.tech/tags/net-core.md>), [thread](<https://devfeed.tech/tags/thread.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>)

### AI overview

`Lazy<T>` defers factory execution until `Value` is accessed. `None` is for single-threaded use and caches factory exceptions; concurrent access is unsafe. `PublicationOnly` lets concurrent callers run the factory independently, publishes the first successful result for everyone, and does not cache exceptions--each factory call that throws still reports its own exception. `ExecutionAndPublication` runs the factory once while other callers wait, and caches any exception, so later accesses keep throwing it. The article says `ExecutionAndPublication` avoids duplicate work and allocations, while `PublicationOnly` may be faster when initialization is cheap, safe to repeat, and lock contention is significant. `LazyInitializer.EnsureInitialized` offers similar publication behaviors without a `Lazy<T>` allocation and does not cache exceptions. A proposed `cacheExceptions` option was approved but was not yet implemented in the described account.

### Source excerpt

In this post I look at how the different `LazyThreadSafetyMode` values work with `Lazy`, and how exceptions are handled for each mode

## CVE-2026-61854 - VoiceSentinel: Race condition in report buffer cleanup can corrupt transcript data and cause unbounded disk growth

DevFeed: [CVE-2026-61854 - VoiceSentinel: Race condition in report buffer cleanup can corrupt transcript data and cause unbounded disk growth](<https://devfeed.tech/articles/cve-2026-61854-voicesentinel-race-condition-in-report-buffer-cleanup-can-corrupt-transcript-data-and-cause-unbounded-disk-growth-109183.md>)

Original publisher: [Read original article](<https://cvefeed.io/vuln/detail/CVE-2026-61854>)

Author: CVEFEED.io

Published: 2026-10-30T18:25:28Z

Content type: news

Language: en

Sources: [Latest High/Critical Vulnerabilitiy Feed](<https://devfeed.tech/sources/latest-high-critical-vulnerabilitiy-feed.md>)

Topics: [race-condition](<https://devfeed.tech/topics/race-condition.md>), [shared mutable state](<https://devfeed.tech/topics/shared-mutable-state.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [locking](<https://devfeed.tech/topics/locking.md>)

Tags: [2026](<https://devfeed.tech/tags/2026.md>), [async](<https://devfeed.tech/tags/async.md>), [asyncio](<https://devfeed.tech/tags/asyncio.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [buffer](<https://devfeed.tech/tags/buffer.md>), [can](<https://devfeed.tech/tags/can.md>), [cause](<https://devfeed.tech/tags/cause.md>), [cleanup](<https://devfeed.tech/tags/cleanup.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [condition](<https://devfeed.tech/tags/condition.md>), [crash](<https://devfeed.tech/tags/crash.md>), [cve](<https://devfeed.tech/tags/cve.md>), [cve-2026-61854](<https://devfeed.tech/tags/cve-2026-61854.md>), [cvss](<https://devfeed.tech/tags/cvss.md>), [data](<https://devfeed.tech/tags/data.md>), [feature](<https://devfeed.tech/tags/feature.md>), [growth](<https://devfeed.tech/tags/growth.md>), [race-condition](<https://devfeed.tech/tags/race-condition.md>), [report](<https://devfeed.tech/tags/report.md>), [transcript](<https://devfeed.tech/tags/transcript.md>)

### AI overview

In VoiceSentinel versions 2.2.1 through before 3.3.1, the optional report buffer can race when retention cleanup rewrites a tenant's transcripts.jsonl while unsynchronized writes append to it. Concurrent cleanup and writes may lose, duplicate, or corrupt transcripts and defeat retention pruning, allowing disk use to grow without bound and potentially crash the host or other services sharing its storage. The issue is reachable during normal operation; worker_count of at least two and shared server_key values increase collisions. The feature is disabled by default, and the description says the issue is fixed in 3.3.1.

### Source excerpt

CVE ID :CVE-2026-61854 Published : Oct. 30, 2026, 6:25 p.m. | 49 minutes ago Description :VoiceSentinel is a real-time voice moderation system for Minecraft servers. From 2.2.1 until 3.3.1, the optional report buffer feature has a race between retention cleanup and normal transcript writes. In `report_buffer.py`, `_maybe_cleanup()` uses an unlocked dictionary for once-per-hour cleanup throttling, allowing simultaneous `_cleanup_tenant()` operations for one tenant. Cleanup reads `transcripts.jsonl` and rewrites it in place without file locking or atomic replacement, while `report_buffer_append_async` uses `asyncio.to_thread` to append without synchronization. In `main.py`, concurrent `_processing_worker` tasks make this reachable in normal operation; `processing.worker_count` of two or more and public-pool servers sharing a `server_key` increase collisions. With `report_buffer.enabled` set to true, racing writes can lose, duplicate or corrupt transcript data and defeat `report_buffer.retention_seconds` pruning, allowing unbounded disk growth that can exhaust storage and crash the host or other services sharing it. The feature is opt-in and disabled by default. This issue is fixed in version 3.3.1. Severity: 8.2 | HIGH Visit the link for more details, such as CVSS details, affected products, timeline, and more...

## An Intro to Threading in Python

DevFeed: [An Intro to Threading in Python](<https://devfeed.tech/articles/an-intro-to-threading-in-python-98857.md>)

Original publisher: [Read original article](<https://realpython.com/intro-to-python-threading/>)

Author: Jim Anderson

Published: 2026-10-24T14:00:00Z

Content type: tutorial

Language: en

Sources: [Real Python](<https://devfeed.tech/sources/real-python.md>)

Topics: [multithreading](<https://devfeed.tech/topics/multithreading.md>), [Python](<https://devfeed.tech/topics/python.md>), [race-condition](<https://devfeed.tech/topics/race-condition.md>), [shared mutable state](<https://devfeed.tech/topics/shared-mutable-state.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [scheduling](<https://devfeed.tech/topics/scheduling.md>)

Tags: [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [deadlocks](<https://devfeed.tech/tags/deadlocks.md>), [locks](<https://devfeed.tech/tags/locks.md>), [python](<https://devfeed.tech/tags/python.md>), [python-threading](<https://devfeed.tech/tags/python-threading.md>), [queues](<https://devfeed.tech/tags/queues.md>), [race-conditions](<https://devfeed.tech/tags/race-conditions.md>), [threading](<https://devfeed.tech/tags/threading.md>), [threads](<https://devfeed.tech/tags/threads.md>)

### AI overview

Python threading can simplify concurrent program design and is most useful for tasks that spend time waiting on external events. In standard CPython builds, the GIL generally prevents Python threads from running CPU-bound code in parallel; the optional free-threaded build introduced in Python 3.13 is an exception. The tutorial shows how to start threads and wait with `join()`, and how `ThreadPoolExecutor` manages a group of workers. It demonstrates a lost update when threads share mutable data, then uses `Lock` to protect the read-modify-write section. A `Lock` used as a context manager is released when the block exits; `RLock` supports repeated acquisition by the same thread. For producer-consumer work, a single-slot lock-based pipeline cannot absorb bursts, while thread-safe `queue.Queue` can buffer messages and block at a configured maximum size; an `Event` signals shutdown, and the consumer drains queued messages before exiting. The article also surveys `Semaphore` for limiting access to finite resources, `Timer` for delayed calls, and `Barrier` for synchronizing a fixed number of threads.

### Source excerpt

Learn how to use Python threading to run tasks concurrently, synchronize threads with locks and queues, and avoid race conditions and deadlocks.

## Immutability is a concurrency strategy, not a style preference

DevFeed: [Immutability is a concurrency strategy, not a style preference](<https://devfeed.tech/articles/immutability-is-a-concurrency-strategy-not-a-style-preference-77003.md>)

Original publisher: [Read original article](<https://ankit-rana.com/logs/64-immutability-is-a-concurrency-strategy/>)

Author: hello@ankit-rana.com

Published: 2026-10-08T00:00:00Z

Content type: article

Language: en

Sources: [Ankit Rana | Mechanical Sympathy](<https://devfeed.tech/sources/ankit-rana-mechanical-sympathy.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Distributed Systems & Parallel Computing](<https://devfeed.tech/topics/distributed-systems-parallel-computing.md>)

Tags: [concurrency](<https://devfeed.tech/tags/concurrency.md>), [design](<https://devfeed.tech/tags/design.md>), [immutability](<https://devfeed.tech/tags/immutability.md>), [java](<https://devfeed.tech/tags/java.md>), [memory-model](<https://devfeed.tech/tags/memory-model.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>), [threads](<https://devfeed.tech/tags/threads.md>)

### AI overview

The article explains how immutable objects and snapshot replacement can prevent readers from observing partially updated shared state. It covers safe publication, defensive copies, allocation tradeoffs, and cases where local mutation or lifecycle-driven mutability remain appropriate.

### Source excerpt

An object that cannot change after construction is safe to share across threads with no lock, no volatile, and no reasoning about happens-before, because there is no write for a reader to miss. That removes an entire category of bug rather than mitigating it. The usual objection is allocation cost, and it is generally the wrong trade to optimise: short lived objects are cheap to collect, while a data race is invisible in testing and reproduces once a quarter in production.

## Optimizing a Lock-Free Ring Buffer

DevFeed: [Optimizing a Lock-Free Ring Buffer](<https://devfeed.tech/articles/optimizing-a-lock-free-ring-buffer-60978.md>)

Original publisher: [Read original article](<https://david.alvarezrosa.com/posts/optimizing-a-lock-free-ring-buffer/>)

Author: David Álvarez Rosa

Published: 2026-03-24T11:51:00Z

Content type: tutorial

Language: en

Sources: [David Álvarez Rosa](<https://devfeed.tech/sources/david-alvarez-rosa.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Deadlock](<https://devfeed.tech/topics/deadlock.md>)

Tags: [atomics](<https://devfeed.tech/tags/atomics.md>), [cpp](<https://devfeed.tech/tags/cpp.md>), [fifo](<https://devfeed.tech/tags/fifo.md>), [latency](<https://devfeed.tech/tags/latency.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [performance](<https://devfeed.tech/tags/performance.md>), [single-threaded](<https://devfeed.tech/tags/single-threaded.md>)

### AI overview

A tutorial builds a single-producer, single-consumer ring buffer from a simple array-based queue through thread-safe and lock-free versions. It explains fixed capacity, FIFO behavior, and using atomics to remove mutual-exclusion overhead for low-latency data sharing between threads.

### Source excerpt

A single-producer single-consumer (SPSC) queue is a great example of how far constraints can take a design. In this post, you will learn how to implement a ring buffer from scratch: start with the simplest design, make it thread-safe, and then gradually remove overhead while preserving FIFO behavior and predictable latency. This pattern is widely used to share data between threads in the lowest-latency environments. What is a ring buffer? § 1You might have run into the term circular buffer, or perhaps cyclic queue. These are simply other names for a ring buffer: a queue where a producer generates data and inserts it into the buffer, and a consumer later pulls it back out, in first-in-first-out order. What makes a ring buffer distinctive is how it stores data and the constraints it enforces. It has a fixed capacity; it neither expands nor shrinks. As a result, when the buffer fills up, the producer must either wait until space becomes available or overwrite entries that have not been read yet, depending on what the application expects. The consumer's job is straightforward: read items as they arrive. When the ring buffer is empty, the consumer has to block, spin, or move on to other work. Each successful read releases a slot the producer can reuse. In the ideal case, the producer stays just a bit ahead, and the system turns into a quiet game of "catch me if you can," with minimal waiting on both sides. Single-threaded ring buffer § Let's start with a single-threaded ring buffer, which is just an array2 and two indices. We leave one slot permanently unused to distinguish "full" from "empty." Push writes to head and advances it; pop reads from tail and advances it. template <typename T, std::size_t N> class RingBufferV1 { std::array<T, N> buffer_; std::size_t head_{0}; std::size_t tail_{0}; }; We can now implement the push (or write) operation3 auto push(const T& value) noexcept -> bool { auto new_head = head_ + 1; if (new_head == buffer_.size()) [[unlikely]] { // Wrap

## BitFields API: Type-Safe Bit Packing for Lock-Free Data Structures

DevFeed: [BitFields API: Type-Safe Bit Packing for Lock-Free Data Structures](<https://devfeed.tech/articles/bitfields-api-type-safe-bit-packing-for-lock-free-data-structures-22396.md>)

Original publisher: [Read original article](<http://rocksdb.org/blog/2025/12/31/bit-fields-api.html>)

Author: Peter Dillinger

Published: 2025-12-31T00:00:00Z

Content type: article

Language: en

Sources: [RocksDB](<https://devfeed.tech/sources/rocksdb.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [rocksdb](<https://devfeed.tech/topics/rocksdb.md>), [Data structures](<https://devfeed.tech/topics/data-structures.md>), [API](<https://devfeed.tech/topics/api.md>), [generic programming](<https://devfeed.tech/topics/generic-programming.md>), [data type](<https://devfeed.tech/topics/data-type.md>), [atomic reference counting](<https://devfeed.tech/topics/atomic-reference-counting.md>)

Tags: [api](<https://devfeed.tech/tags/api.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [bit-packing](<https://devfeed.tech/tags/bit-packing.md>), [blog](<https://devfeed.tech/tags/blog.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [cache](<https://devfeed.tech/tags/cache.md>), [data-structures](<https://devfeed.tech/tags/data-structures.md>), [hash-table](<https://devfeed.tech/tags/hash-table.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [rocksdb](<https://devfeed.tech/tags/rocksdb.md>), [state](<https://devfeed.tech/tags/state.md>), [type-safe](<https://devfeed.tech/tags/type-safe.md>)

### AI overview

RocksDB's BitFields API packs typed fields into a single integer so lock-free structures can update more state with atomic operations while avoiding hand-maintained masks and shifts. In HyperClockCache, each slot's counters, state, and hit flag share a 64-bit value; the migration reportedly made the implementation easier to understand and helped algorithms make progress through atomic work updates. The C++ API offers typed field declarations, CAS support, and transforms that combine supported additions/subtractions or bitwise operations into one atomic operation, with debug-build overflow checks. The authors report no runtime overhead versus handwritten manipulation in RocksDB and identical assembly in one verified case. A LifoSem optimization relying on overflow between fields could not be expressed as efficiently under the API's overflow checks, so it accessed the underlying representation. A variant has been proposed for folly; broader acceptance and possible API improvements remain future work.

### Source excerpt

Modern concurrent data structures increasingly rely on atomic operations to avoid the overhead of locking. A valuable but under-utilized technique for maximizing the effectiveness of atomic operations is bit packing--fitting multiple logical fields into a single atomic variable for algorithmic simplicity and efficiency. However, language support for bit packing does not guarantee dense packing, and manually managing bit manipulation quickly becomes error-prone, especially when dealing with complex state machines. To address this in RocksDB, we have developed a reusable BitFields API, a type-safe, zero-overhead abstraction for bit packing in C++. This works in conjunction with clean wrappers for std::atomic for powerful and relatively safe bit-packing of atomic data. For broader use, a variant of the code has been proposed for adding to folly. The Problem: Managing Packed Bit Fields Consider HyperClockCache, an essentially lock-free cache implementation in RocksDB, which was refactored to use this BitFields API. It is a hash table built on slots that can each hold a cache entry and relevant metadata. For atomic simplicity and efficiency, all the essential metadata for each slot is packed into a single 64-bit value: The reference count and eviction metadata are together encoded into acquire and release counters, 30 bits each. The possible states of {empty, under construction/destruction, occupied+visible, and occupied+invisible} are encoded into three state bits (instead of two, for easier decoding and manipulation). A hit bit is used for secondary cache integration. Traditionally, you might write code like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // Old approach: manual bit manipulation constexpr uint64_t kAcquireCounterShift = 0; constexpr uint64_t kReleaseCounterShift = 30; constexpr uint64_t kCounterMask = 0x3FFFFFFF; constexpr uint64_t kHitBitShift = 60; constexpr uint64_t k

## Fearless Concurrency Ep.6: Understanding Rust ARC for Efficient Multithreading

DevFeed: [Fearless Concurrency Ep.6: Understanding Rust ARC for Efficient Multithreading](<https://devfeed.tech/articles/fearless-concurrency-ep-6-understanding-rust-arc-for-efficient-multithreading-22270.md>)

Original publisher: [Read original article](<https://www.ardanlabs.com/blog/2024/11/fearless-concurrency-ep6-understanding-rust-arc-for-efficient-multithreading.html>)

Published: 2024-11-21T00:00:00Z

Content type: article

Language: en

Sources: [William Kennedy](<https://devfeed.tech/sources/william-kennedy.md>)

Topics: [atomic reference counting](<https://devfeed.tech/topics/atomic-reference-counting.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [Rust](<https://devfeed.tech/topics/rust.md>), [multithreading](<https://devfeed.tech/topics/multithreading.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Distributed Systems & Parallel Computing](<https://devfeed.tech/topics/distributed-systems-parallel-computing.md>)

Tags: [applications](<https://devfeed.tech/tags/applications.md>), [arc](<https://devfeed.tech/tags/arc.md>), [arc-best-practices](<https://devfeed.tech/tags/arc-best-practices.md>), [arc-for-performance](<https://devfeed.tech/tags/arc-for-performance.md>), [arc-in-rust](<https://devfeed.tech/tags/arc-in-rust.md>), [arc-memory-management](<https://devfeed.tech/tags/arc-memory-management.md>), [arc-ownership-model](<https://devfeed.tech/tags/arc-ownership-model.md>), [arc-shared-resources](<https://devfeed.tech/tags/arc-shared-resources.md>), [arc-vs-garbage-collection](<https://devfeed.tech/tags/arc-vs-garbage-collection.md>), [arc-with-mutex](<https://devfeed.tech/tags/arc-with-mutex.md>), [arc-with-rwlock](<https://devfeed.tech/tags/arc-with-rwlock.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [atomic-reference-counting](<https://devfeed.tech/tags/atomic-reference-counting.md>), [best-practices](<https://devfeed.tech/tags/best-practices.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrency-in-rust](<https://devfeed.tech/tags/concurrency-in-rust.md>), [configuration](<https://devfeed.tech/tags/configuration.md>), [connection-pool](<https://devfeed.tech/tags/connection-pool.md>), [database](<https://devfeed.tech/tags/database.md>), [efficient-multithreading-rust](<https://devfeed.tech/tags/efficient-multithreading-rust.md>), [garbage-collection](<https://devfeed.tech/tags/garbage-collection.md>), [global](<https://devfeed.tech/tags/global.md>), [heap](<https://devfeed.tech/tags/heap.md>), [implementation](<https://devfeed.tech/tags/implementation.md>), [interior-mutability-arc](<https://devfeed.tech/tags/interior-mutability-arc.md>), [large](<https://devfeed.tech/tags/large.md>), [lightweight](<https://devfeed.tech/tags/lightweight.md>), [lightweight-memory-management](<https://devfeed.tech/tags/lightweight-memory-management.md>), [memory](<https://devfeed.tech/tags/memory.md>), [multithreading](<https://devfeed.tech/tags/multithreading.md>), [multithreading-with-arc](<https://devfeed.tech/tags/multithreading-with-arc.md>), [ownership](<https://devfeed.tech/tags/ownership.md>), [rust](<https://devfeed.tech/tags/rust.md>), [rust-arc-tutorial](<https://devfeed.tech/tags/rust-arc-tutorial.md>), [rust-arc-use-cases](<https://devfeed.tech/tags/rust-arc-use-cases.md>), [rust-concurrency-tools](<https://devfeed.tech/tags/rust-concurrency-tools.md>), [rust-shared-ownership](<https://devfeed.tech/tags/rust-shared-ownership.md>), [rust-thread-safe-programming](<https://devfeed.tech/tags/rust-thread-safe-programming.md>), [thread-safe-data-sharing](<https://devfeed.tech/tags/thread-safe-data-sharing.md>)

### AI overview

Rust ARC shares a heap-allocated value across threads by cloning a pointer and incrementing its reference count; dropping each pointer decrements the count, and the value is destroyed when the count reaches zero. This avoids copying the underlying data and can suit high fan-out sharing, such as sharing configuration or a database connection pool. The excerpt also mentions combining ARC with interior mutability for thread-safe updates and flags circular references as a pitfall. It presents ARC as shared ownership without a traditional garbage collector; the excerpt does not identify the interior-mutability types or give their usage details.

### Source excerpt

Introduction: Welcome to Episode 6 of the Fearless Concurrency in Rust series! In this episode, we explore the powerful concept of ARC (Atomic Reference Counting) and its critical role in managing shared resources in multithreaded Rust programs. By leveraging ARC, developers can safely share ownership of data across threads without relying on a traditional garbage collector, enabling efficient, flexible, and scalable concurrency. What is ARC?: Understanding Atomic Reference Counting as a lightweight, manual garbage collection system.

## Fearless Concurrency Ep.4: Understanding Mutexes and Thread Safety in Rust

DevFeed: [Fearless Concurrency Ep.4: Understanding Mutexes and Thread Safety in Rust](<https://devfeed.tech/articles/fearless-concurrency-ep-4-understanding-mutexes-and-thread-safety-in-rust-22261.md>)

Original publisher: [Read original article](<https://www.ardanlabs.com/blog/2024/10/fearless-concurrency-ep4-understanding-mutexes-and-thread-safety-in-rust.html>)

Published: 2024-10-25T00:00:00Z

Content type: article

Language: en

Sources: [William Kennedy](<https://devfeed.tech/sources/william-kennedy.md>)

Topics: [Rust](<https://devfeed.tech/topics/rust.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [locking](<https://devfeed.tech/topics/locking.md>), [Memory Safety](<https://devfeed.tech/topics/memory-safety.md>), [synchronization](<https://devfeed.tech/topics/synchronization.md>), [race-condition](<https://devfeed.tech/topics/race-condition.md>), [Distributed Systems & Parallel Computing](<https://devfeed.tech/topics/distributed-systems-parallel-computing.md>), [undefined\_behavior](<https://devfeed.tech/topics/undefined-behavior.md>), [typesafety](<https://devfeed.tech/topics/typesafety.md>)

Tags: [avoiding-race-conditions-in-rust](<https://devfeed.tech/tags/avoiding-race-conditions-in-rust.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrency-and-memory-management-in-rust](<https://devfeed.tech/tags/concurrency-and-memory-management-in-rust.md>), [concurrency-in-rust](<https://devfeed.tech/tags/concurrency-in-rust.md>), [managing-shared-data-in-rust](<https://devfeed.tech/tags/managing-shared-data-in-rust.md>), [mutex](<https://devfeed.tech/tags/mutex.md>), [mutex-and-drop-trait-in-rust](<https://devfeed.tech/tags/mutex-and-drop-trait-in-rust.md>), [mutexes-in-rust](<https://devfeed.tech/tags/mutexes-in-rust.md>), [race-conditions](<https://devfeed.tech/tags/race-conditions.md>), [rust](<https://devfeed.tech/tags/rust.md>), [rust-concurrency-best-practices](<https://devfeed.tech/tags/rust-concurrency-best-practices.md>), [rust-concurrency-guide](<https://devfeed.tech/tags/rust-concurrency-guide.md>), [rust-drop-trait-in-concurrency](<https://devfeed.tech/tags/rust-drop-trait-in-concurrency.md>), [rust-multithreading-tutorial](<https://devfeed.tech/tags/rust-multithreading-tutorial.md>), [rust-mutex-example](<https://devfeed.tech/tags/rust-mutex-example.md>), [rust-mutex-vs-lock](<https://devfeed.tech/tags/rust-mutex-vs-lock.md>), [rust-ownership-and-borrowing-in-concurrency](<https://devfeed.tech/tags/rust-ownership-and-borrowing-in-concurrency.md>), [rust-thread-safety](<https://devfeed.tech/tags/rust-thread-safety.md>), [rust-thread-safety-without-garbage-collection](<https://devfeed.tech/tags/rust-thread-safety-without-garbage-collection.md>), [safety](<https://devfeed.tech/tags/safety.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>), [thread-synchronization-in-rust](<https://devfeed.tech/tags/thread-synchronization-in-rust.md>), [understanding-poisoned-mutexes-in-rust](<https://devfeed.tech/tags/understanding-poisoned-mutexes-in-rust.md>)

### AI overview

The excerpt explains how Rust's ownership and borrowing rules govern variables shared across threads, including exclusive access and ensuring values outlive the threads that use them. It describes mutexes as enforcing mutual exclusion and says Rust's scope-based resource cleanup releases locks automatically. It also notes that the episode covers poisoned mutexes, which can result when a thread panics while holding a lock. The excerpt does not identify the specific Rust types or features by name.

### Source excerpt

Introduction: Welcome to Episode 4 of Fearless Concurrency in Rust! In this episode, we explore how Rust's ownership and borrowing rules impact multithreaded programming, focusing on the complexities of managing memory in a concurrent environment. We'll break down how Rust's strict borrowing and ownership model ensures safety and prevents common pitfalls like data races and undefined behavior, making it an ideal choice for building reliable multithreaded applications. Thread Safety and Ownership: Managing variables across threads using Rust's ownership rules.

## Fearless Concurrency Ep.2: Managing Threaded Programs and Data Races in Rust

DevFeed: [Fearless Concurrency Ep.2: Managing Threaded Programs and Data Races in Rust](<https://devfeed.tech/articles/fearless-concurrency-ep-2-managing-threaded-programs-and-data-races-in-rust-22259.md>)

Original publisher: [Read original article](<https://www.ardanlabs.com/blog/2024/09/fearless-concurrency-ep2-managing-threaded-programs-and-data-races-in-rust.html>)

Published: 2024-09-26T00:00:00Z

Content type: article

Language: en

Sources: [William Kennedy](<https://devfeed.tech/sources/william-kennedy.md>)

Topics: [Rust](<https://devfeed.tech/topics/rust.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [race-condition](<https://devfeed.tech/topics/race-condition.md>), [Distributed Systems & Parallel Computing](<https://devfeed.tech/topics/distributed-systems-parallel-computing.md>), [shared mutable state](<https://devfeed.tech/topics/shared-mutable-state.md>)

Tags: [atomics](<https://devfeed.tech/tags/atomics.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrency-in-rust](<https://devfeed.tech/tags/concurrency-in-rust.md>), [creating-threads-in-rust](<https://devfeed.tech/tags/creating-threads-in-rust.md>), [managing-threads-in-rust](<https://devfeed.tech/tags/managing-threads-in-rust.md>), [operating-system](<https://devfeed.tech/tags/operating-system.md>), [ownership](<https://devfeed.tech/tags/ownership.md>), [preventing-race-conditions-in-rust](<https://devfeed.tech/tags/preventing-race-conditions-in-rust.md>), [race-conditions](<https://devfeed.tech/tags/race-conditions.md>), [rust](<https://devfeed.tech/tags/rust.md>), [rust-atomic-operations](<https://devfeed.tech/tags/rust-atomic-operations.md>), [rust-borrow-checker-for-threads](<https://devfeed.tech/tags/rust-borrow-checker-for-threads.md>), [rust-concurrency-tutorial](<https://devfeed.tech/tags/rust-concurrency-tutorial.md>), [rust-concurrent-programming](<https://devfeed.tech/tags/rust-concurrent-programming.md>), [rust-data-race-prevention](<https://devfeed.tech/tags/rust-data-race-prevention.md>), [rust-join-handles](<https://devfeed.tech/tags/rust-join-handles.md>), [rust-multithreading](<https://devfeed.tech/tags/rust-multithreading.md>), [rust-ownership-system](<https://devfeed.tech/tags/rust-ownership-system.md>), [rust-thread-safety](<https://devfeed.tech/tags/rust-thread-safety.md>), [rust-threading-basics](<https://devfeed.tech/tags/rust-threading-basics.md>), [safety](<https://devfeed.tech/tags/safety.md>), [std-thread-spawn-in-rust](<https://devfeed.tech/tags/std-thread-spawn-in-rust.md>), [thread-lifecycle-in-rust](<https://devfeed.tech/tags/thread-lifecycle-in-rust.md>), [threading](<https://devfeed.tech/tags/threading.md>)

### AI overview

The excerpt explains how Rust's std::thread::spawn starts operating-system threads and how joining their handles ensures they finish before the main program exits; handles can also return values. Rust's ownership and borrowing rules restrict shared access to multiple immutable references or one mutable reference, allowing the borrow checker to prevent unsafe data races. The episode also covers atomics for modifying shared state safely. The standard-library threading interface is presented as straightforward, but without platform-specific features such as thread priority or CPU affinity. The supplied text ends mid-sentence, so this overview reflects only the available excerpt.

### Source excerpt

Introduction: Welcome to Episode 2 of the Fearless Concurrency in Rust series! In this episode, Herbert Wolverson dives into the fundamentals of threading in Rust, demonstrating how to use Rust's threading capabilities effectively while maintaining safety. The focus is on using std::thread to spawn threads, preventing data races, and ensuring efficient, reliable multithreaded execution. Creating Threads in Rust: How to spawn and manage operating system threads using std::thread::spawn. Handling Data Races: Rust's borrow checker and ownership system preventing unsafe data access across threads.

## Fearless Concurrency Ep.1: Rust's Approach to Safe and Manageable Multithreading

DevFeed: [Fearless Concurrency Ep.1: Rust's Approach to Safe and Manageable Multithreading](<https://devfeed.tech/articles/fearless-concurrency-ep-1-rust-s-approach-to-safe-and-manageable-multithreading-22258.md>)

Original publisher: [Read original article](<https://www.ardanlabs.com/blog/2024/09/fearless-concurrency-ep1-rusts-approach-to-safe-and-manageable-multithreading.html>)

Published: 2024-09-12T00:00:00Z

Content type: article

Language: en

Sources: [William Kennedy](<https://devfeed.tech/sources/william-kennedy.md>)

Topics: [multithreading](<https://devfeed.tech/topics/multithreading.md>), [Rust](<https://devfeed.tech/topics/rust.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [synchronization](<https://devfeed.tech/topics/synchronization.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [c/c++](<https://devfeed.tech/topics/c-c-plus-plus.md>), [scheduling](<https://devfeed.tech/topics/scheduling.md>)

Tags: [basics](<https://devfeed.tech/tags/basics.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [challenge](<https://devfeed.tech/tags/challenge.md>), [challenges](<https://devfeed.tech/tags/challenges.md>), [compile-time-safety-in-rust](<https://devfeed.tech/tags/compile-time-safety-in-rust.md>), [complexity](<https://devfeed.tech/tags/complexity.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrency-in-rust](<https://devfeed.tech/tags/concurrency-in-rust.md>), [concurrency-pitfalls-in-c-plus-plus](<https://devfeed.tech/tags/concurrency-pitfalls-in-c-plus-plus.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [context](<https://devfeed.tech/tags/context.md>), [efficient-threading-in-rust](<https://devfeed.tech/tags/efficient-threading-in-rust.md>), [go](<https://devfeed.tech/tags/go.md>), [go-vs-rust-concurrency](<https://devfeed.tech/tags/go-vs-rust-concurrency.md>), [herbert-wolverson-fearless-concurrency](<https://devfeed.tech/tags/herbert-wolverson-fearless-concurrency.md>), [history](<https://devfeed.tech/tags/history.md>), [introduction](<https://devfeed.tech/tags/introduction.md>), [managing-threads-in-rust](<https://devfeed.tech/tags/managing-threads-in-rust.md>), [memory-safety-in-rust](<https://devfeed.tech/tags/memory-safety-in-rust.md>), [model](<https://devfeed.tech/tags/model.md>), [multithreading](<https://devfeed.tech/tags/multithreading.md>), [mutexes-and-locks-in-rust](<https://devfeed.tech/tags/mutexes-and-locks-in-rust.md>), [operating-systems](<https://devfeed.tech/tags/operating-systems.md>), [preventing-data-races-in-rust](<https://devfeed.tech/tags/preventing-data-races-in-rust.md>), [programming](<https://devfeed.tech/tags/programming.md>), [race-conditions-in-rust](<https://devfeed.tech/tags/race-conditions-in-rust.md>), [rust](<https://devfeed.tech/tags/rust.md>), [rust-concurrency-tools](<https://devfeed.tech/tags/rust-concurrency-tools.md>), [rust-memory-management](<https://devfeed.tech/tags/rust-memory-management.md>), [rust-multithreading](<https://devfeed.tech/tags/rust-multithreading.md>), [rust-ownership-system](<https://devfeed.tech/tags/rust-ownership-system.md>), [rust-programming-threads](<https://devfeed.tech/tags/rust-programming-threads.md>), [rust-thread-management-tips](<https://devfeed.tech/tags/rust-thread-management-tips.md>), [rust-thread-safety](<https://devfeed.tech/tags/rust-thread-safety.md>), [rust-vs-c-plus-plus-multithreading](<https://devfeed.tech/tags/rust-vs-c-plus-plus-multithreading.md>), [safe-concurrency-in-rust](<https://devfeed.tech/tags/safe-concurrency-in-rust.md>), [thread](<https://devfeed.tech/tags/thread.md>), [threading](<https://devfeed.tech/tags/threading.md>), [threads](<https://devfeed.tech/tags/threads.md>)

### AI overview

Rust uses OS-native threads with little additional overhead, but shared data still requires careful coordination. The excerpt describes common multithreading hazards such as race conditions and garbled output, and explains that Rust's ownership and borrowing rules prevent unsynchronized concurrent mutation. Mutexes and locks provide explicit coordination when threads need access to shared data; Rust's type system checks safety constraints at compile time. The discussion contrasts threads with older, resource-intensive process forking and mentions C++ and Go examples of concurrency problems, but gives no detailed comparative feature analysis.

### Source excerpt

Introduction: In Episode 1 of the Fearless Concurrency in Rust series, Herbert Wolverson introduces the foundational concept of threads in programming, tracing their origins and evolution while demonstrating how Rust handles concurrency in a safer, more manageable way. He explores the history of threads and their role in enabling programs to perform multiple tasks simultaneously, comparing Rust's threading model with traditional approaches in C++ and Go. Thread Basics and History: Understanding how threads function within operating systems and their development over time.

## Concurrent Programming in Kotlin: Ensuring Thread Safety with Mutex

DevFeed: [Concurrent Programming in Kotlin: Ensuring Thread Safety with Mutex](<https://devfeed.tech/articles/concurrent-programming-in-kotlin-ensuring-thread-safety-with-mutex-23873.md>)

Original publisher: [Read original article](<https://engineering.premise.com/concurrent-programming-in-kotlin-ensuring-thread-safety-with-mutex-5d9c6b80644b?source=rss----c5fada0a103d---4>)

Author: Kwabena Bio Berko

Published: 2023-07-18T03:33:24Z

Content type: article

Language: en

Sources: [Engineering at Premise](<https://devfeed.tech/sources/engineering-at-premise-medium.md>)

Topics: [locking](<https://devfeed.tech/topics/locking.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [race-condition](<https://devfeed.tech/topics/race-condition.md>), [shared mutable state](<https://devfeed.tech/topics/shared-mutable-state.md>), [synchronization](<https://devfeed.tech/topics/synchronization.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [multithreading](<https://devfeed.tech/topics/multithreading.md>), [Coroutines](<https://devfeed.tech/topics/coroutines.md>), [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [suspend function](<https://devfeed.tech/topics/suspend-function.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [android-engineer](<https://devfeed.tech/tags/android-engineer.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [component](<https://devfeed.tech/tags/component.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrent-programming](<https://devfeed.tech/tags/concurrent-programming.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [coroutine](<https://devfeed.tech/tags/coroutine.md>), [coroutines](<https://devfeed.tech/tags/coroutines.md>), [data](<https://devfeed.tech/tags/data.md>), [database](<https://devfeed.tech/tags/database.md>), [engineering](<https://devfeed.tech/tags/engineering.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [mobile-app-development](<https://devfeed.tech/tags/mobile-app-development.md>), [mutex](<https://devfeed.tech/tags/mutex.md>), [safety](<https://devfeed.tech/tags/safety.md>), [software](<https://devfeed.tech/tags/software.md>), [thread](<https://devfeed.tech/tags/thread.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>)

### AI overview

The article describes using Kotlin's Mutex to prevent concurrent refresh calls from duplicating a remote fetch and database write. It presents two behaviors: a call can check whether the Mutex is locked and skip refresh while it is in use, or use the suspending `withLock` lambda to wait until the lock is released. Restricting access to critical sections helps prevent race conditions and keep shared data consistent, but locking too much code can serialize work, reduce parallelism, and slow the application. The article recommends limiting Mutex use to sections that require exclusive access.

### Source excerpt

By Kwabena Bio Berko, Android Engineer Photo by Chris Ried on Unsplash I have recently been experimenting with mutual exclusion(Mutex), a concept in software engineering to solve race conditions when accessing shared resources. Let's assume we have a component with a refresh function that can be accessed from multiple threads or coroutines: https://medium.com/media/e19aa2a9d57bc105b841d28061a199b8/href In the implementation of this component, the function retrieves data from a remote resource and inserts it into the local database. However, these operations need to be atomic. Now, imagine if 10 threads call this function simultaneously, or even a few milliseconds apart. What happens? If you guessed that we make 10 network calls and 10 database IO operations to save the items, then you would be right, as confirmed by the below test: https://medium.com/media/9b279658dbf87021068ee21a913dc80e/hrefhttps://medium.com/media/81cdc164ad807fd45df77389c00bd4cc/href But that's not what we want. It's definitely not resource-friendly. To address this issue, we can use a Mutex. As the name suggests, a Mutex provides mutual exclusion for a specific portion of your code, imposing restrictions on the access to that portion in situations where multiple threads or coroutines may attempt to access it concurrently. In essence, Mutex allows only one thread or coroutine to work within the confines of that portion of the code at any given time. By introducing a Mutex in our refresh function, we can ensure that only one thread is executing the critical sections of the code, preventing race conditions and ensuring atomicity of the operations. https://medium.com/media/9d88a802b4c73f14ceb4d5527158af5d/href In the example above, whenever the refresh function is called, we check to see if the Mutex is already locked or been used. If not, we lock it and then perform our network call and save the results in our local database. This means that whenever another thread or coroutine calls this refresh

## Make sure to update your StateFlow safely in Kotlin!

DevFeed: [Make sure to update your StateFlow safely in Kotlin!](<https://devfeed.tech/articles/make-sure-to-update-your-stateflow-safely-in-kotlin-25522.md>)

Original publisher: [Read original article](<https://patrykkosieradzki.com/make-sure-to-update-your-stateflow-safely-in-kotlin>)

Published: 2021-07-25T00:00:00Z

Content type: article

Language: en

Sources: [Patryk Kosieradzki](<https://devfeed.tech/sources/patryk-kosieradzki.md>)

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [coroutines-flow](<https://devfeed.tech/topics/coroutines-flow.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [flow](<https://devfeed.tech/tags/flow.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [safely](<https://devfeed.tech/tags/safely.md>), [stateflow](<https://devfeed.tech/tags/stateflow.md>), [update](<https://devfeed.tech/tags/update.md>)

### AI overview

Updating a `MutableStateFlow` with `value.copy(...)` can lose concurrent changes: another thread may update a different property after the copy is made but before it is emitted. The excerpt recommends `update`, `updateAndGet`, and `getAndUpdate`, which take a function that derives the new state from the current value. It describes `update` as applying that function and using `compareAndSet`; if the value changed concurrently, it retries until the update succeeds. The excerpt does not explain differences among the three methods.

### Source excerpt

StateFlow is a common choice for storing app state in Android, e.g., view state. But do you know how to use it correctly?

## False Sharing

DevFeed: [False Sharing](<https://devfeed.tech/articles/false-sharing-24842.md>)

Original publisher: [Read original article](<https://alidg.me/blog/2020/5/1/false-sharing>)

Author: Alimate

Published: 2020-05-01T00:00:00Z

Content type: article

Language: en

Sources: [Ali Dehghan - Kemikit](<https://devfeed.tech/sources/ali-dehghan-kemikit.md>)

Topics: [performance-engineering](<https://devfeed.tech/topics/performance-engineering.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>)

Tags: [atomic](<https://devfeed.tech/tags/atomic.md>), [benchmark](<https://devfeed.tech/tags/benchmark.md>), [jvm](<https://devfeed.tech/tags/jvm.md>), [latency](<https://devfeed.tech/tags/latency.md>), [layout](<https://devfeed.tech/tags/layout.md>), [measuring](<https://devfeed.tech/tags/measuring.md>), [memory](<https://devfeed.tech/tags/memory.md>), [multithreading](<https://devfeed.tech/tags/multithreading.md>), [padding](<https://devfeed.tech/tags/padding.md>), [sharing](<https://devfeed.tech/tags/sharing.md>), [threads](<https://devfeed.tech/tags/threads.md>), [throughput](<https://devfeed.tech/tags/throughput.md>)

### AI overview

The excerpt benchmarks eight atomic counters incremented by eight threads, each targeting a distinct counter, and reports about 170 ns per call for the initial layout. Despite no logical counter contention, shared memory layout can affect performance: adding padding between counters produces surprising latency changes. The excerpt describes using JOL to inspect object layout and padding counters until each occupies a separate 64-byte area, but it ends before reporting the final benchmark result or explaining the full measurement.

### Source excerpt

Measuring false-sharing effect on latency and throughput

## Thread Local Randoms in Java

DevFeed: [Thread Local Randoms in Java](<https://devfeed.tech/articles/thread-local-randoms-in-java-24841.md>)

Original publisher: [Read original article](<https://alidg.me/blog/2020/4/24/thread-local-random>)

Author: Alimate

Published: 2020-04-24T00:00:00Z

Content type: article

Language: en

Sources: [Ali Dehghan - Kemikit](<https://devfeed.tech/sources/ali-dehghan-kemikit.md>)

Topics: [Benchmark](<https://devfeed.tech/topics/benchmark.md>), [Java](<https://devfeed.tech/topics/java.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Algorithms](<https://devfeed.tech/topics/algorithms.md>), [locking](<https://devfeed.tech/topics/locking.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [atomics](<https://devfeed.tech/tags/atomics.md>), [benchmark](<https://devfeed.tech/tags/benchmark.md>), [cas](<https://devfeed.tech/tags/cas.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [generation](<https://devfeed.tech/tags/generation.md>), [generator](<https://devfeed.tech/tags/generator.md>), [global](<https://devfeed.tech/tags/global.md>), [java](<https://devfeed.tech/tags/java.md>), [linear](<https://devfeed.tech/tags/linear.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [memory](<https://devfeed.tech/tags/memory.md>), [ordering](<https://devfeed.tech/tags/ordering.md>), [performance](<https://devfeed.tech/tags/performance.md>), [random](<https://devfeed.tech/tags/random.md>), [retry](<https://devfeed.tech/tags/retry.md>), [shared-mutable-state](<https://devfeed.tech/tags/shared-mutable-state.md>), [synchronization](<https://devfeed.tech/tags/synchronization.md>), [thread](<https://devfeed.tech/tags/thread.md>)

### AI overview

The excerpt attributes poor concurrent throughput in shared random generation to contention: Java's implementation updates a shared seed with atomic compare-and-set retries, which can fail repeatedly under load. A thread-local approach avoids shared mutable state and the associated atomicity and memory-ordering costs; in the reported benchmark, it achieved almost twice the throughput of the author's simple implementation. The built-in random generator still outperformed both approaches. The excerpt begins to describe a further optimization--keeping only each thread's latest value instead of a full per-thread generator copy--but cuts off before giving its implementation or results.

### Source excerpt

Benchmarking regular randoms against thread-local ones!

## Lock Striping

DevFeed: [Lock Striping](<https://devfeed.tech/articles/lock-striping-24834.md>)

Original publisher: [Read original article](<https://alidg.me/blog/2020/1/11/lock-striping>)

Author: Alimate

Published: 2020-01-11T00:00:00Z

Content type: article

Language: en

Sources: [Ali Dehghan - Kemikit](<https://devfeed.tech/sources/ali-dehghan-kemikit.md>)

Topics: [synchronization](<https://devfeed.tech/topics/synchronization.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Data structures](<https://devfeed.tech/topics/data-structures.md>)

Tags: [concurrent](<https://devfeed.tech/tags/concurrent.md>), [data-structure](<https://devfeed.tech/tags/data-structure.md>), [lock](<https://devfeed.tech/tags/lock.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [locks](<https://devfeed.tech/tags/locks.md>), [map](<https://devfeed.tech/tags/map.md>), [performance](<https://devfeed.tech/tags/performance.md>)

### AI overview

The excerpt describes a thread-safe hashtable built with ordinary locks, contrasting its approach with lock-free designs based on CAS. In the coarse-grained version, one lock enforces exclusive access for all operations. The map starts with a fixed number of buckets, selects a bucket using the key's hash modulo the bucket count, and inserts or updates entries. To address performance degradation as stored elements outgrow the buckets, it proposes resizing when an average bucket-size threshold is exceeded; resizing requires copying the current table. The excerpt does not provide the completed resize implementation or results comparing coarse- and fine-grained synchronization.

### Source excerpt

Let's see how well a fine-grained synchronized concurrent data structure performs compared to its coarse-grained counterpart

## Friday Q&A 2017-10-27: Locks, Thread Safety, and Swift: 2017 Edition

DevFeed: [Friday Q&A 2017-10-27: Locks, Thread Safety, and Swift: 2017 Edition](<https://devfeed.tech/articles/friday-q-a-2017-10-27-locks-thread-safety-and-swift-2017-edition-30624.md>)

Original publisher: [Read original article](<http://www.mikeash.com/pyblog/friday-qa-2017-10-27-locks-thread-safety-and-swift-2017-edition.html>)

Author: Mike Ash

Published: 2017-10-27T11:28:00Z

Content type: article

Language: en

Sources: [Mike Ash](<https://devfeed.tech/sources/mike-ash.md>)

Topics: [locking](<https://devfeed.tech/topics/locking.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Swift](<https://devfeed.tech/topics/swift.md>), [scheduling](<https://devfeed.tech/topics/scheduling.md>)

Tags: [locks](<https://devfeed.tech/tags/locks.md>), [swift](<https://devfeed.tech/tags/swift.md>), [thread](<https://devfeed.tech/tags/thread.md>), [thread-safety](<https://devfeed.tech/tags/thread-safety.md>)

### AI overview

The article recommends DispatchQueue as the usual Swift locking choice: its sync/async closures simplify protected access, propagate return values and thrown errors, and support reader-writer patterns, though queues have some overhead and lack features such as recursion and condition variables. It explains why Apple's old OSSpinLock was deprecated: priority inversion could let a high-priority thread spin while preventing the low-priority lock holder from running; os_unfair_lock is the low-level replacement, with priority handling but no fairness. The article warns that pthread_mutex_t, pthread_rwlock_t, and os_unfair_lock are noncopyable value types that must be stored and passed carefully; pthread locks also need explicit initialization and destruction. For explicit lock/unlock APIs, defer or a callback wrapper helps ensure unlocking on early returns and thrown errors. os_unfair_lock may suit cases where per-lock overhead matters and fairness is unnecessary; pthread_mutex offers features such as recursion, while the article sees little reason to use pthread_rwlock or OperationQueue specifically for locking.

### Source excerpt

Back in the dark ages of Swift 1, I wrote an article about locks and thread safety in Swift. The march of time has made it fairly obsolete, and reader Seth Willits suggested I update it for the modern age, so here it is! (Read More)

## Can Reordering of Release/Acquire Operations Introduce Deadlock?

DevFeed: [Can Reordering of Release/Acquire Operations Introduce Deadlock?](<https://devfeed.tech/articles/can-reordering-of-release-acquire-operations-introduce-deadlock-21011.md>)

Original publisher: [Read original article](<https://preshing.com/20170612/can-reordering-of-release-acquire-operations-introduce-deadlock>)

Author: Jeff Preshing

Published: 2017-06-12T11:34:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [c/c++](<https://devfeed.tech/topics/c-c-plus-plus.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [iteration](<https://devfeed.tech/topics/iteration.md>), [Process](<https://devfeed.tech/topics/process.md>)

Tags: [2](<https://devfeed.tech/tags/2.md>), [about](<https://devfeed.tech/tags/about.md>), [architectures](<https://devfeed.tech/tags/architectures.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [but](<https://devfeed.tech/tags/but.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [can](<https://devfeed.tech/tags/can.md>), [changes](<https://devfeed.tech/tags/changes.md>), [comes](<https://devfeed.tech/tags/comes.md>), [compare](<https://devfeed.tech/tags/compare.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [cpu](<https://devfeed.tech/tags/cpu.md>), [deadlock](<https://devfeed.tech/tags/deadlock.md>), [don-t](<https://devfeed.tech/tags/don-t.md>), [either](<https://devfeed.tech/tags/either.md>), [example](<https://devfeed.tech/tags/example.md>), [exchange](<https://devfeed.tech/tags/exchange.md>), [free](<https://devfeed.tech/tags/free.md>), [operations](<https://devfeed.tech/tags/operations.md>), [release](<https://devfeed.tech/tags/release.md>)

### AI overview

The post argues that a release store followed by an acquire spinlock attempt may be reordered under acquire/release rules, apparently allowing a thread to hold two locks and creating deadlock risk. The author believes C++ draft N4659 §4.7.2:18's recommendation that atomic updates eventually become visible rules out moving the store past a potentially infinite wait. Compiler Explorer showed no reordering by three major compilers, but the author says this is not proof. An update notes the standard says "should," not "must," and applies the same argument to two threads busy-waiting on each other's signals. The author concludes acquire/release is not inherently more deadlock-prone, while acknowledging the wording is weak and inviting contrary evidence.

### Source excerpt

I wasn't planning to write about lock-free programming again, but a commenter named Mike recently asked an interesting question on my Acquire and Release Semantics post from 2012. It's a question I wondered about years ago, but could never really reconcile until (possibly) now. A quick recap: A read-acquire operation cannot be reordered, either by the compiler or the CPU, with any read or write operation that follows it in program order. A write-release operation cannot be reordered with any read or write operation that precedes it in program order. Those rules don't prevent the reordering of a write-release followed by a read-acquire. For example, in C++, if A and B are std::atomic<int>, and we write: A.store(1, std::memory_order_release); int b = B.load(std::memory_order_acquire); ...the compiler is free to reorder those statements, as if we had written: int b = B.load(std::memory_order_acquire); A.store(1, std::memory_order_release); And that's fair. Why the heck not? On many architectures, including x86, the CPU could perform this reordering anyway. Well, here's where Mike's question comes in. What if A and B are spinlocks? Let's say that the spinlock is initially 0. To lock it, we repeatedly attempt a compare-and-swap, with acquire semantics, until it changes from 0 to 1. To unlock it, we simply set it back to 0, with release semantics. Now, suppose Thread 1 does the following: // Lock A int expected = 0; while (!A.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock A A.store(0, std::memory_order_release); // Lock B while (!B.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock B B.store(0, std::memory_order_release); Meanwhile, Thread 2 does the following: // Lock B int expected = 0; while (!B.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Lock A while (!A.compare_exchange_weak(expected, 1, std::memory_order_acquire)) { expected = 0; } // Unlock A A.

## Constructors Are Not Thread-Safe

DevFeed: [Constructors Are Not Thread-Safe](<https://devfeed.tech/articles/constructors-are-not-thread-safe-32220.md>)

Original publisher: [Read original article](<https://bruceeckel.com/2017/01/13/constructors-are-not-thread-safe/>)

Author: Bruce Eckel

Published: 2017-01-13T00:00:00Z

Content type: article

Language: en

Sources: [Bruce Eckel - Computing Thoughts](<https://devfeed.tech/sources/bruce-eckel-computing-thoughts.md>)

Topics: [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [constructor](<https://devfeed.tech/topics/constructor.md>), [Java](<https://devfeed.tech/topics/java.md>), [locking](<https://devfeed.tech/topics/locking.md>)

Tags: [argument](<https://devfeed.tech/tags/argument.md>), [arguments](<https://devfeed.tech/tags/arguments.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [block](<https://devfeed.tech/tags/block.md>), [class](<https://devfeed.tech/tags/class.md>), [collect](<https://devfeed.tech/tags/collect.md>), [collectors](<https://devfeed.tech/tags/collectors.md>), [completablefuture](<https://devfeed.tech/tags/completablefuture.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [constructor](<https://devfeed.tech/tags/constructor.md>), [counter](<https://devfeed.tech/tags/counter.md>), [factory](<https://devfeed.tech/tags/factory.md>), [java](<https://devfeed.tech/tags/java.md>), [java-language](<https://devfeed.tech/tags/java-language.md>), [language](<https://devfeed.tech/tags/language.md>), [object](<https://devfeed.tech/tags/object.md>), [specification](<https://devfeed.tech/tags/specification.md>), [thread](<https://devfeed.tech/tags/thread.md>), [threads](<https://devfeed.tech/tags/threads.md>)

### AI overview

Java object construction can still encounter shared-memory races when constructors use shared state. In the examples, incrementing a plain static int produced many duplicate IDs across concurrent tasks; replacing it with AtomicInteger eliminated observed duplicates. A constructor can also receive a shared, non-thread-safe argument: two tasks using the same Unsafe counter produced collisions, while a synchronized block on a shared static lock or a synchronized static factory method serialized access and produced none in the tests. Constructors themselves cannot be declared synchronized; the text explains that synchronization around construction must use a shared lock such as the class object. The examples show that a class may be used concurrently in ways its constructor cannot detect, so shared state passed into it also needs protection.

### Source excerpt

When you imagine the construction process, it can be easy to think that it's thread-safe. After all, no one can even see the new object before it finishes initialization, so how could there be contention over that object? Indeed, the Java Language Specification (JLS) confidently states: "There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work.

## A Resizable Concurrent Map

DevFeed: [A Resizable Concurrent Map](<https://devfeed.tech/articles/a-resizable-concurrent-map-21005.md>)

Original publisher: [Read original article](<https://preshing.com/20160222/a-resizable-concurrent-map>)

Author: Jeff Preshing

Published: 2016-02-22T13:05:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [race-condition](<https://devfeed.tech/topics/race-condition.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [synchronization](<https://devfeed.tech/topics/synchronization.md>)

Tags: [blocking](<https://devfeed.tech/tags/blocking.md>), [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [delete](<https://devfeed.tech/tags/delete.md>), [hash](<https://devfeed.tech/tags/hash.md>), [hash-table](<https://devfeed.tech/tags/hash-table.md>), [java](<https://devfeed.tech/tags/java.md>), [linear-probing](<https://devfeed.tech/tags/linear-probing.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [map](<https://devfeed.tech/tags/map.md>), [maps](<https://devfeed.tech/tags/maps.md>), [migration](<https://devfeed.tech/tags/migration.md>), [open-addressing](<https://devfeed.tech/tags/open-addressing.md>), [resize](<https://devfeed.tech/tags/resize.md>), [table](<https://devfeed.tech/tags/table.md>), [thread](<https://devfeed.tech/tags/thread.md>)

### AI overview

Junction's Linear map extends the simpler Crude map with resizing and deletion while permitting concurrent operations. It uses open addressing and linear probing, but stores hashed keys and keeps the table, size mask, and remaining-cell counter behind one root pointer. When the counter signals overpopulation, migration copies entries into a larger table. To avoid losing concurrent updates, migration replaces old cell values with Redirect markers using compare-and-swap; operations that encounter a marker are directed to the new table. In the version described, concurrent assignments cannot modify the new table until migration finishes, and gets that encounter Redirect help complete migration rather than immediately reading from the new table. Erase marks a value as NullValue but retains its hash, so deleted cells are reclaimed during migration. The excerpt says the invertible hash limits supported keys to integers and raw pointers.

### Source excerpt

In an earlier post, I showed how to implement the "world's simplest lock-free hash table" in C++. It was so simple that you couldn't even delete entries or resize the table. Well, a few years have passed since then, and I've recently written some concurrent maps without those limitations. You'll find them in my Junction project on GitHub. Junction contains several concurrent maps - even the 'world's simplest' is there, under the name ConcurrentMap_Crude. For brevity, let's call that one the Crude map. In this post, I'll explain the difference between the Crude map and Junction's Linear map. Linear is the simplest Junction map that supports both resize and delete. You can review the original post for an explanation of how the Crude map works. To recap: It's based on open addressing and linear probing. That means it's basically a big array of keys and values using a linear search. When inserting or looking up a given key, you hash the key to determine where to begin the search. Concurrent inserts and lookups are permitted. Junction's Linear map is based on the same principle, except that when the array gets too full, its entire contents are migrated to a new, larger array. When the migration completes, the old table is replaced with the old one. So, how do we achieve that while still allowing concurrent operations? The Linear map's approach is based on Cliff Click's non-blocking hash map in Java, but has a few differences. The Data Structure First, we need to modify our data structure a little bit. The original Crude map had two data members: A pointer m_cells and an integer m_sizeMask. The Linear map instead has a single data member m_root, which points to a Table structure followed by the cells themselves in a single, contiguous memory block. In the Table structure, there's a new shared counter cellsRemaining, initially set to 75% of the table size. Whenever a thread tries to insert a new key, it decrements cellsRemaining first. If it decrements cellsRemaining below

## Git Concurrency in GitHub Desktop

DevFeed: [Git Concurrency in GitHub Desktop](<https://devfeed.tech/articles/git-concurrency-in-github-desktop-69763.md>)

Original publisher: [Read original article](<https://github.blog/news-insights/the-library/git-concurrency-in-github-desktop/>)

Author: Amy Palamountain

Published: 2015-10-20T07:00:00Z

Content type: article

Language: en

Sources: [GitHub Blog](<https://devfeed.tech/sources/github-engineering.md>)

Topics: [GitHub Desktop](<https://devfeed.tech/topics/github-desktop.md>), [Git](<https://devfeed.tech/topics/git.md>), [Deadlock](<https://devfeed.tech/topics/deadlock.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>)

Tags: [concurrency](<https://devfeed.tech/tags/concurrency.md>), [desktop](<https://devfeed.tech/tags/desktop.md>), [git](<https://devfeed.tech/tags/git.md>), [github](<https://devfeed.tech/tags/github.md>), [github-desktop](<https://devfeed.tech/tags/github-desktop.md>), [news-insights](<https://devfeed.tech/tags/news-insights.md>), [the-library](<https://devfeed.tech/tags/the-library.md>)

### AI overview

GitHub Desktop uses a queued concurrency model to keep repository operations responsive and protect repository integrity. It runs eligible operations in parallel while requiring exclusive operations, such as commits, to wait for active work to finish. The approach accommodates both Git's lock-file behavior and libgit2's thread-safety limits, and the article reports improved stability and performance after its introduction.

### Source excerpt

Careful use of concurrency is particularly important when writing responsive desktop applications. Typically, complex operations are executed on background threads. This results in an app that remains responsive to user...

## You Can Do Any Kind of Atomic Read-Modify-Write Operation

DevFeed: [You Can Do Any Kind of Atomic Read-Modify-Write Operation](<https://devfeed.tech/articles/you-can-do-any-kind-of-atomic-read-modify-write-operation-21003.md>)

Original publisher: [Read original article](<https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation>)

Author: Jeff Preshing

Published: 2015-04-02T11:20:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [atomic](<https://devfeed.tech/tags/atomic.md>), [atomics](<https://devfeed.tech/tags/atomics.md>), [cas](<https://devfeed.tech/tags/cas.md>), [clang](<https://devfeed.tech/tags/clang.md>), [compiler](<https://devfeed.tech/tags/compiler.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [memory](<https://devfeed.tech/tags/memory.md>), [mutex](<https://devfeed.tech/tags/mutex.md>), [operations](<https://devfeed.tech/tags/operations.md>)

### AI overview

C++11's `compare_exchange_weak` can implement custom atomic read-modify-write operations through a compare-and-swap loop: compute a new value, retry if another thread changed the shared value, and stop when the update succeeds or a condition makes it a no-op. The article demonstrates multiplication, a conditional decrement-or-halving operation, and updating two values packed into one atomic object. Such loops are atomic; they are lock-free only when the compare-and-swap implementation is lock-free, and weak compare-exchange may fail spuriously. The C++11 standard does not guarantee every atomic type is lock-free, so compiler and target support matter. Packing data into an integer atomic may help, but memory-ordering guarantees still need consideration, especially when passing non-atomic data between threads.

### Source excerpt

Atomic read-modify-write operations - or "RMWs" - are more sophisticated than atomic loads and stores. They let you read from a variable in shared memory and simultaneously write a different value in its place. In the C++11 atomic library, all of the following functions perform an RMW: std::atomic<>::fetch_add() std::atomic<>::fetch_sub() std::atomic<>::fetch_and() std::atomic<>::fetch_or() std::atomic<>::fetch_xor() std::atomic<>::exchange() std::atomic<>::compare_exchange_strong() std::atomic<>::compare_exchange_weak() fetch_add, for example, reads from a shared variable, adds another value to it, and writes the result back - all in one indivisible step. You can accomplish the same thing using a mutex, but a mutex-based version wouldn't be lock-free. RMW operations, on the other hand, are designed to be lock-free. They'll take advantage of lock-free CPU instructions whenever possible, such as ldrex/strex on ARMv7. A novice programmer might look at the above list of functions and ask, "Why does C++11 offer so few RMW operations? Why is there an atomic fetch_add, but no atomic fetch_multiply, no fetch_divide and no fetch_shift_left?" There are two reasons: Because there is very little need for those RMW operations in practice. Try not to get the wrong impression of how RMWs are used. You can't write safe multithreaded code by taking a single-threaded algorithm and turning each step into an RMW. Because if you do need those operations, you can easily implement them yourself. As the title says, you can do any kind of RMW operation! Compare-and-Swap: The Mother of All RMWs Out of all the available RMW operations in C++11, the only one that is absolutely essential is compare_exchange_weak. Every other RMW operation can be implemented using that one. It takes a minimum of two arguments: shared.compare_exchange_weak(T& expected, T desired, ...); This function attempts to store the desired value to shared, but only if the current value of shared matches expected. It return

## Semaphores are Surprisingly Versatile

DevFeed: [Semaphores are Surprisingly Versatile](<https://devfeed.tech/articles/semaphores-are-surprisingly-versatile-21001.md>)

Original publisher: [Read original article](<https://preshing.com/20150316/semaphores-are-surprisingly-versatile>)

Author: Jeff Preshing

Published: 2015-03-16T09:50:00Z

Content type: article

Language: en

Sources: [Jeff Preshing](<https://devfeed.tech/sources/jeff-preshing.md>)

Topics: [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [locking](<https://devfeed.tech/topics/locking.md>), [Deadlock](<https://devfeed.tech/topics/deadlock.md>)

Tags: [atomic](<https://devfeed.tech/tags/atomic.md>), [class](<https://devfeed.tech/tags/class.md>), [cpu](<https://devfeed.tech/tags/cpu.md>), [cpu-time](<https://devfeed.tech/tags/cpu-time.md>), [dijkstra](<https://devfeed.tech/tags/dijkstra.md>), [dining](<https://devfeed.tech/tags/dining.md>), [environments](<https://devfeed.tech/tags/environments.md>), [event](<https://devfeed.tech/tags/event.md>), [exclusive](<https://devfeed.tech/tags/exclusive.md>), [github](<https://devfeed.tech/tags/github.md>), [implement](<https://devfeed.tech/tags/implement.md>), [ios](<https://devfeed.tech/tags/ios.md>), [kernel](<https://devfeed.tech/tags/kernel.md>), [library](<https://devfeed.tech/tags/library.md>), [lightweight](<https://devfeed.tech/tags/lightweight.md>), [like](<https://devfeed.tech/tags/like.md>), [linux](<https://devfeed.tech/tags/linux.md>), [lock](<https://devfeed.tech/tags/lock.md>), [macos](<https://devfeed.tech/tags/macos.md>), [versatile](<https://devfeed.tech/tags/versatile.md>)

### AI overview

The article shows how semaphores and atomic operations can implement several lightweight C++11 synchronization primitives through a "box office/bouncer" pattern: atomics track state and decide whether threads proceed or wait, while a semaphore queues and releases waiters. Examples include a mutex, auto-reset event, read-write lock, dining philosophers solution, and a semaphore with partial spinning. The implementations can avoid kernel calls when uncontended; the lightweight semaphore can spin briefly before sleeping. A portable Semaphore class maps to native semaphores on several platforms. The author reports that, on one Windows PC, an auto-reset event was 10x faster than a condition-variable version and the test suite benefited significantly from partial spinning, while noting the fixed 10,000-iteration spin strategy may not suit every environment. The article also acknowledges that conventional mutex and condition-variable approaches are often preferred because semaphore techniques can be error prone.

### Source excerpt

In multithreaded programming, it's important to make threads wait. They must wait for exclusive access to a resource. They must wait when there's no work available. One way to make threads wait - and put them to sleep inside the kernel, so that they no longer take any CPU time - is with a semaphore. I used to think semaphores were strange and old-fashioned. They were invented by Edsger Dijkstra back in the early 1960s, before anyone had done much multithreaded programming, or much programming at all, for that matter. I knew that a semaphore could keep track of available units of a resource, or function as a clunky kind of mutex, but that seemed to be about it. My opinion changed once I realized that, using only semaphores and atomic operations, it's possible to implement all of the following primitives: A Lightweight Mutex A Lightweight Auto-Reset Event Object A Lightweight Read-Write Lock Another Solution to the Dining Philosophers Problem A Lightweight Semaphore With Partial Spinning Not only that, but these implementations share some desirable properties. They're lightweight, in the sense that some operations happen entirely in userspace, and they can (optionally) spin for a short period before sleeping in the kernel. You'll find all of the C++11 source code on GitHub. Since the standard C++11 library does not include semaphores, I've also provided a portable Semaphore class that maps directly to native semaphores on Windows, MacOS, iOS, Linux and other POSIX environments. You should be able to drop any of these primitives into almost any existing C++11 project. A Semaphore Is Like a Bouncer Imagine a set of waiting threads, lined up in a queue - much like a lineup in front of a busy nightclub or theatre. A semaphore is like a bouncer at the front of the lineup. He only allows threads to proceed when instructed to do so. Each thread decides for itself when to join the queue. Dijkstra called this the P operation. P originally stood for some funny-sounding Dutch wo

[Next page](<https://devfeed.tech/topics/thread-safe-data-sharing.md?cursor=WyIyMDE1LTAzLTE2VDA5OjUwOjAwKzAwOjAwIiwgImMwMWFiMjNjLWIzMjctNDg0MS1iZDNjLWJlYWIzZTg5YjY4YSJd>)