[swift-evolution] [Proposal] Property behaviors
Michel Fortin
michel.fortin at michelf.ca
Sat Dec 19 11:11:02 CST 2015
Le 18 déc. 2015 à 18:56, Kevin Ballard <kevin at sb.org> a écrit :
> On Fri, Dec 18, 2015, at 07:18 AM, Michel Fortin wrote:
>> The reason I'm suggesting implementing synchronized as a behaviour instead of a type is because I found out with experience that synchronization should be related to variables, not types. Types exists in a vacuum while variables are bound to a context, and a synchronized access pattern should usually stay encapsulated in a particular context (struct or class). A Synchronized<T> should not be copied or passed by reference and used out of its context; a property behaviour makes that just impossible, which is better.
>
> I don't really understand what you're trying to say here. The goal you describe (of not being able to copy or pass the synchronized value around) is satisfied by having some way to declare a struct that cannot be copied (but can be moved, because moves are always fine as long as there's no code (e.g. other threads) that is still expecting the value to be at its original location). Describing synchronized behavior as a non-copyable type like this actually works extremely well in practice.
In essence, synchronization is an access policy for a variable. It's somewhat similar to `let` granting you only access to the getter, or the `Delayed` property behaviour that lets you use the setter only once.
Synchronization is an access policy stipulating that you should only use the getter and setter of the variable while the current thread has locked the associated mutex. While you could enforce that at runtime with fatalErrors in the setter and getter whenever the mutex is not locked (similar to `Delayed`), it's simply more convenient to enforce it at compile time by requiring a closure.
I acknowledge a type such as Synchronized<T> will work fine for that too (assuming non-copyablility). I just think the modeling is slightly off. Synchronization is an access policy, not a data type, and it should be modeled in a similar manner to the other access policies in the language.
Language support for concurrency is out of scope for Swift 3, so it's perhaps premature to think about that now... but I can't help but think it'll have to work this way anyway the day Swift introduces a safe concurrency model.
--
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca
More information about the swift-evolution
mailing list