attaswift / BTree

Fast sorted collections for Swift using in-memory B-trees

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Thread safety

wildthink opened this issue · comments

Given the copy-on-write semantics, is reading the original tree thread safe?

let set_1: SortedSet = ...
var set_2 = set_1
set_2.insert(new_element)

Can we safely assume that set_1 can safely be read in a different thread while set_2 is mutated?

@wildthink CoW mechanisms are separate from thread-safety. Thread safety is usually a bad idea for structures like these because it severely impacts performance in a negative way whilst usually providing no benefits. You can always add an Foundation.Lock to your code for interacting with these trees.

Disclaimer: Not a/the library dev.

I guess what I'm asking is "In making a copy of A is A mutated in the process?" So if I have a copy of A, say B and proceed to mutate B triggering a copy-on-write A should be unaffected even internally. Is this not true?

Yes. That's true.

@wildthink Yep, @Joannis is right! set_1 is safe to access in a different thread.

BTree has the same thread-safety guarantees as Array, Dictionary etc -- COW copying, read-only operations are thread safe, but mutations aren't.