One of the selling points of immutable data structures is that they are automatically parallelizable. If no mutation is going on, then references to a functional data structure can be passed around between threads without any locking.
I got to thinking about how functional data structures would be implemented in c++. Suppose that we have a reference count on each node of our data structure. (Functional data structures share structure between old and updated members of a data structure, so nodes would not belong uniquely to one particular data structure.)
The problem is that if reference counts are being updated in different threads, then our data structure is no longer thread safe. And attaching a mutex to every single node is both expensive and defeats the purpose of using immutable data structures for concurrency.
Is there a way to make concurrent immutable data structures work in c++ (and other non-garbage collected environments)?
It's usually said that immutable data structures are more "friendly" for concurrency programming. The explanation is that if a data structure is mutable and one thread modifies it, then another thread will "see" the previous mode of the data structure.
Immutable data structures are usually designed so that common operations can be performed quite quickly. When a change is made, a new version of the data structure is created by referring to the old version, or part of it, and adding information about what changed.
The Functional Programming is more inclined towards creating Functions in a mathematical sense. The immutability helps us to take a mathematical approach and create pure functions.
An immutable object is an object whose state cannot be modified after it is created. Examples of native JavaScript values that are immutable are numbers and strings. Examples of native JavaScript values that are mutable include objects, arrays, functions, classes, sets, and maps.
There are lock-free reference counting algorithms, see, e.g. Lock-Free Reference Counting, Atomic Reference Counting Pointers.
Also note that C++0x (which will probably become C++11 soon) contains atomic integer types especially for purposes like this one.
Well, garbage collected languages also have the issue of multi-threaded environments (and it is not easy for mutable structures).
You have forgotten that unlike arbitrary data, counters can be incremented and decremented atomically, so a mutex would be unnecessary. It still means that cache synchro between processors need be maintained, which may cost badly if a single node keeps being updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With