Concurrent collections¶
flpit.concurrent has thread-safe collections modelled on .NET's System.Collections.Concurrent. They work on
regular and free-threaded CPython.
ConcurrentDictionary¶
counts[word] = counts.get(word, 0) + 1 loses updates when two threads read the same old value.
add_or_update does the read-modify-write atomically:
from flpit.concurrent import ConcurrentDictionary
from flpit.task import Task
counts = ConcurrentDictionary[str, int]()
words = ["a", "b", "a"] * 1000
def count(words: list[str]) -> None:
for word in words:
counts.add_or_update(word, 1, lambda _, n: n + 1) # atomic: no lost updates
Task.wait_all([Task.run(count, words) for _ in range(4)]) # four threads, one dictionary
assert counts["a"] == 8000 and counts["b"] == 4000
It is also a regular Python mapping: in, [key], len() and iteration work as for dict. Iterating works on a
snapshot, so it never breaks while other threads modify the dictionary.
get_or_add(key, factory) creates a value only for a missing key. The factory is a callable that receives the key,
because the dictionary knows its own value type, so even list values need one:
cache = ConcurrentDictionary[str, list[int]]()
history = cache.get_or_add("ada", lambda key: []) # the factory runs only if the key is missing
history.append(1)
assert cache["ada"] == [1]
The other atomic operations are try_update and try_remove. CDict[str, int]() is a short alias.
Queue, stack and bag¶
from flpit.concurrent import ConcurrentQueue, ConcurrentStack
queue = ConcurrentQueue([1, 2, 3])
stack = ConcurrentStack([1, 2, 3])
assert queue.try_dequeue() == (True, 1) # FIFO: the oldest first
assert stack.try_pop() == (True, 3) # LIFO: the newest first
assert ConcurrentQueue[int]().try_dequeue() == (False, None) # empty: no exception
ConcurrentQueue(CQueue): first in, first out.try_dequeuereturns the oldest item.ConcurrentStack: last in, first out.push_rangeandtry_pop_rangemove several items at once, kept together.ConcurrentBag: unordered. A thread gets its own items back first, which makes it cheap for workers that consume what they produce, and otherwise takes another thread's oldest.
Instead of raising when empty, try_dequeue, try_pop and try_take return (True, item) or (False, None).
More programs:
examples/concurrent/.