Reference

std/core/shared

std/core/src/shared.trb

A type is a value: assigning it, passing it and capturing it is a copy. A shared type is the exception - its instances have an identity and everybody who holds one sees the same object. Resources (File, Socket, Channel, Window) are declared as shared type.

Shared<Value> is the ad hoc version: it puts a value in a place that can be held by several owners.

var pages: Shared<Map<String, Page>> = Shared([:])
var renderer = Renderer(cache: pages)
var preloader = Preloader(cache: pages)      // Both work on the same map

The usual rule applies: no var path, no mutation. A const binding or a parameter that is not var is a read-only view of the object (it can still change, but not through this path). Shared objects never cross task boundaries.

fn isSame

native fn isSame<Object>(first: Object, second: Object): Bool

true if both are the same object. (== is about content and does not exist for shared objects.)

Only shared objects have an identity, so this is only callable on them. On a value the answer would expose whether the implementation shares storage, and the compiler rejects the call ("isSame compares identity, and a Point is a value. Use ==.") - a named special case, because the language has no bound that says "shared".

type Shared

shared type Shared<Value>

A box that puts a value in a place several owners can hold, without declaring a whole shared type for it.

Examples

var counter: Shared<Int> = Shared 0
counter.update { count => count + 1 }
print counter.value

Related

  • isSame - whether two Shared boxes (or any other shared objects) are the same one.

field value

var value: Value

The boxed value. A const binding or a parameter that is not var is a read-only view of it: the value can still change through another owner's path, just not through this one.

fn update

var fn update(change: Transform<Value, Value>)

counter.update { count => count + 1 }