开发者

Can functional/immutable data structures still be useful for concurrency in a non-garbage collected context?

开发者 https://www.devze.com 2023-03-31 18:15 出处:网络
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 bet

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 immu开发者_如何学Ctable data structures for concurrency.

Is there a way to make concurrent immutable data structures work in c++ (and other non-garbage collected environments)?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消