# Understanding Swift's value type thread safety

**URL:** <https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406>\
**Category:** Using Swift\
**Tags:** concurrency\
**Created:** [October 23, 2020, 3:16pm UTC](https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406 "2020-10-23T15:16:04Z")\
**Posts on this page:** 1\
**Showing post:** 32

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [October 26, 2020, 4:52pm UTC](https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406/32 "2020-10-26T16:52:45Z")

</div>

Quotation of the week:

> [@rob](#):
>
> It's unfortunate how easy it is to (silently) lose the safety that value types provide when handing them off to an escaping closure.

> the lack of explicit signalling required is a potential footgun. `shared` / `__block` would help but I wonder if something at the point of use/capture would be even better (similar to explicit `self` in a closure).

I thought of reasons why that might be better (e.g. `[shared store]` in the capture list) before my coffee but now I can't retrieve them. 😉 Why do you think so?

Downsides:

- When there are multiple closures in the function body, the variable is boxed once per declaration site, not once per closure. Not sure what it would mean to notate it just one of two closures.
- That's a lot of syntactic weight to add to the closure, especially xN closures.

Of course I'd also like all global and `static` `var`s to be marked `shared` (0.5 x 😉).

> [@rob](#):
>
> Is a mutation in an escaping closure required to trigger the storage change or will any access also cause the change?

Yes, good point any access causes the change, thanks for asking.

> [@rob](#):
>
> I'm experimenting with _reading_ in the closure and mutating in the function scope and thread sanitizer complains.

You can of course do that with by explicitly capturing the variable, which creates a distinct copy, but then of course the value is not shared with the function body:

```swift
        DispatchQueue.global().async { [store] in // <=== HERE
            for _ in 1...iterations {
                _ = store
            }
        }

```

or, simplified:

```swift
var store = 0
let f = { [store] in store }
store += 1
print(f()) // prints 0

```

If you actually want to share and mutate the value across concurrent computations, as others have pointed out, you need synchronization.

---

_[View the full topic](https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406)._
