From b025cf269d2e07e179be4a0e34d936862dc640c2 Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Thu, 2 Jan 2025 20:29:55 -0500 Subject: Use `holding` blocks for mutexed data instead of lambdas --- docs/mutexed.md | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) (limited to 'docs') diff --git a/docs/mutexed.md b/docs/mutexed.md index eebf9015..97357f39 100644 --- a/docs/mutexed.md +++ b/docs/mutexed.md @@ -1,24 +1,34 @@ # Mutexed Data To serve the general case of synchronizing access to shared datastructures, -Tomo uses the `mutexed` keyword, which returns a function which can be used -to ensure that all access to a datastructure is guarded by a mutex: +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: ```tomo -with_nums := mutexed [10, 20, 30] +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] thread := Thread.new(func(): - with_nums(func(nums:&[Int]): + holding nums: nums:insert(30) - ) ) -with_nums(func(nums:&[Int]): +holding nums: nums:insert(40) -) thread:join() ``` -Without having a mutex guard, the code above could run into concurrency issues -leading to data corruption. +Without using a mutex, the code above could run into concurrency issues leading +to data corruption. -- cgit v1.2.3