Shared
import "std/concurrency" (included in import "std") · namespace std.concurrency
State shared between threads without one lock in front of everything.
ThreadLocal<T>: a value per thread, made by itsinitthe first time a thread asks. Each thread keeps its values in its own memory, sogetandsettake no lock: about 30 ns on one thread, and still that with many at once, where a map behind a lock slows as threads queue for it. A thread's values are let go when it exits.ConcurrentMap<K, V>: a map in 16 shards, each with its own lock, so threads on different keys seldom wait for each other.mergeandcomputeIfAbsentread and write a key in one step. Onlysize,keysandclearvisit every shard.LruCache<K, V>: at mostcapacityentries, forgetting the least recently used first; withttlMs, entries also expire. A cache of 1024 entries or more is split into 16 shards (each with an equal share of the room). A hit costs about 230 ns, against 180 ns for aConcurrentMapthat never forgets;hits(),misses()andevictions()say how it is doing.AtomicLongandAtomicBoolare in async.
import "std"
fn main() {
let scratch = new ThreadLocal<StringBuilder>(fn() -> StringBuilder { return new StringBuilder() })
let hits = new ConcurrentMap<string, long>()
let threads = new Array<Thread>()
for (t in 0..4) {
threads.push(Thread.spawn(fn() {
for (i in 0..100) {
scratch.get().append("x") // this thread's own builder
hits.merge(i % 2 == 0 ? "even" : "odd", 1, fn(a: long, b: long) -> long { return a + b })
}
}))
}
for (th in threads) { th.join() }
print("${hits.get("even")} ${hits.get("odd")} ${scratch.get().length()}")
}200 200 0LruCache
import "std"
fn main() {
let c = new LruCache<string, int>(2)
c.put("a", 1)
c.put("b", 2)
print(c.getOr("a", 0)) // a is now the most recently used
c.put("c", 3) // so b is forgotten to make room
print(c.containsKey("b"))
print(c.getOrPut("d", fn(k: string) -> int { return 4 }))
print("${c.keys()} hits ${c.hits()} misses ${c.misses()} evicted ${c.evictions()}")
}1
false
4
["d", "c"] hits 1 misses 1 evicted 2class ThreadLocal<T>
A value per thread: the first get() on a thread makes it with init. Each thread keeps its values in its own memory, so get and set take no lock; a thread's values are let go when it exits.
Constructors
new ThreadLocal(init: fn() -> T)
Methods
fn get() -> T— This thread's value (made byinitthe first time).fn set(v: T)— Sets this thread's value.fn has() -> bool— Whether this thread has a value yet.fn remove()— Forgets this thread's value (the next get() makes a new one).
class ConcurrentMap<K, V>
A thread-safe map in 16 shards, each a HashMap with its own lock: threads on different keys seldom wait for each other, and nothing ever locks the whole map but size(), keys() and clear().
Constructors
new ConcurrentMap()
Methods
fn get(key: K) -> Vfn getOr(key: K, fallback: V) -> V— The value forkey, orfallback.fn put(key: K, value: V)fn containsKey(key: K) -> boolfn remove(key: K) -> bool— Removeskey; whether it was there.fn computeIfAbsent(key: K, make: fn(K) -> V) -> V— The value forkey, made bymake(once, under the key's lock) when missing.fn merge(key: K, value: V, combine: fn(V, V) -> V) -> V— Putsvalue, or combines it with the value there (combine(old, value)); the result.fn size() -> intfn isEmpty() -> boolfn keys() -> Array<K>— The keys at this moment (a copy).fn clear()
class LruShard<K, V>
One shard of an LruCache: keys and values in parallel arrays, kept dense (a removed entry's place is taken by the last one, so nothing removed stays referenced); the recency links and expiry times in C (GravLru). Not thread-safe on its own: LruCache holds its lock.
Constructors
new LruShard(capacity: int)
Fields
capacity: inthits: long = 0misses: long = 0evictions: long = 0
Methods
fn size() -> intfn find(key: K, now: long) -> int— The entry's place, or -1 (expired ones are dropped;now0: no times kept).fn valueAt(i: int) -> Vfn getOr(key: K, now: long, fallback: V) -> V— The value forkey(now the most recent), orfallback; counts the hit or miss.fn put(key: K, value: V, expiresAt: long)fn remove(key: K) -> boolfn clear()fn keys(out: Array<K>)
class LruCache<K, V>
A cache of at most capacity entries that forgets the least recently used one first; with ttlMs, entries also expire that many milliseconds after they were put. Thread-safe: a large cache (1024 entries or more) is split into 16 shards, each with its own lock and an equal share of the room, so threads seldom wait for each other (the order forgotten is then per shard).
Constructors
new LruCache(capacity: int, ttlMs: long = 0)
Fields
capacity: intttlMs: long
Methods
fn getOr(key: K, fallback: V) -> V— The value forkey(now the most recently used), orfallback.fn containsKey(key: K) -> bool— Whetherkeyis cached (and not expired); does not count as a use.fn put(key: K, value: V)fn putFor(key: K, value: V, ttlMs: long)— Puts with its own time to live (0: none).fn getOrPut(key: K, make: fn(K) -> V) -> V— The value forkey, made bymakewhen missing or expired (under the key's lock:makemust not use this cache).fn remove(key: K) -> bool— Removeskey; whether it was there.fn size() -> intfn isEmpty() -> boolfn clear()fn keys() -> Array<K>— The keys, most recently used first (per shard).fn hits() -> long— Lookups that found an entry, ones that did not, and entries forgotten for room.fn misses() -> longfn evictions() -> long