2025-01-02 13:29:21 -08:00
|
|
|
# Mutexed Data
|
|
|
|
|
|
|
|
To serve the general case of synchronizing access to shared datastructures,
|
2025-01-02 17:29:55 -08:00
|
|
|
Tomo uses the `mutexed` keyword, which allocates a mutex and some heap memory
|
|
|
|
for a value. Access to the heap-allocated value's memory can only be obtained
|
|
|
|
by using a `holding` block. `holding` blocks ensure that the underlying mutex
|
|
|
|
is locked before entering the block and unlocked before leaving it (even if a
|
|
|
|
short-circuiting control flow statement like `return` or `stop` is used). Here
|
|
|
|
is a simple example:
|
2025-01-02 13:29:21 -08:00
|
|
|
|
|
|
|
```tomo
|
2025-01-02 17:29:55 -08:00
|
|
|
nums := mutexed [10, 20, 30]
|
|
|
|
|
|
|
|
>> nums
|
|
|
|
= mutexed [Int]<0x12345678> : mutexed([Int])
|
|
|
|
|
|
|
|
holding nums:
|
|
|
|
# Inside this block, the type of `nums` is `&[Int]`
|
|
|
|
>> nums
|
|
|
|
= &[10, 20, 30] : &[Int]
|
2025-01-02 13:29:21 -08:00
|
|
|
|
|
|
|
thread := Thread.new(func():
|
2025-01-02 17:29:55 -08:00
|
|
|
holding nums:
|
2025-01-02 13:29:21 -08:00
|
|
|
nums:insert(30)
|
|
|
|
)
|
|
|
|
|
2025-01-02 17:29:55 -08:00
|
|
|
holding nums:
|
2025-01-02 13:29:21 -08:00
|
|
|
nums:insert(40)
|
|
|
|
|
|
|
|
thread:join()
|
|
|
|
```
|
|
|
|
|
2025-01-02 17:29:55 -08:00
|
|
|
Without using a mutex, the code above could run into concurrency issues leading
|
|
|
|
to data corruption.
|