iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔒

Achieving Sendability with OSAllocatedUnfairLock as an Alternative to Swift Actors

に公開

🧑‍⚕️ "Hey, make that object Sendable."
🧑 "Ah... okay..."

Summary

  • As part of preparing for Swift 6, you might need to make objects conform to Sendable.
  • In Swift, this is typically solved by using an actor.
  • However, when you can't use an actor, you can make it Sendable by protecting access to its state using your own locks.
  • I would like to introduce a locking method using OSAllocatedUnfairLock, which is available on Apple platforms.
  • Those who want to make a certain object Sendable, but have encountered a situation where using an actor for that purpose is inconvenient.
  • Those who want to know how to make an object Sendable other than by using an actor.
  • Those who are writing code that uses @unchecked Sendable while protecting access to state with os_unfair_lock.
  • Those who want to know about locking methods on Apple platforms other than NSLock.

Data Race Occurrence

Let's consider a Counter like the following.

Counter.swift
import Foundation

final class Counter {
    private var value = 0
    
    func increment() -> Int {
        value += 1
        return value
    }
}

Let's try executing this from two Task instances like this.

let counter = Counter()

Task.detached {
    print(counter.increment())  // 🍎
}

Task.detached {
    print(counter.increment())  // 🍏
}

When you execute this, there is a possibility of getting the following output patterns.

🍎 🍏
1 1 ❌ Data race
1 2 ✅ As intended
2 1 ✅ As intended
2 2 ❌ Data race

Depending on the timing of execution, a data race might occur, such as both 🍎 and 🍏 outputting 1 or 2. To avoid this, we want to "protect the value"—in other words, make it Sendable.

Protecting Values with an actor

In environments where Swift Concurrency is available, the first thing that comes to mind for "protecting values" is an actor (or global actor). Let's try changing the Counter into an actor.

Counter.swift
import Foundation

actor Counter {
    private var value = 0
    
    func increment() -> Int {
        value += 1
        return value
    }
}

The only difference is changing Counter from a final class to an actor.

- final class Counter {
+ actor Counter {

Let's try executing this from two Task instances like this.

let counter = Counter()

Task.detached {
    print(await counter.increment())  // 🍎
}

Task.detached {
    print(await counter.increment())  // 🍏
}

When you execute this, there is a possibility of getting the following output patterns.

🍎 🍏
1 2 ✅ As intended
2 1 ✅ As intended

By using an actor, data races where both 🍎 and 🍏 might output 1 or 2 no longer occur.

"Making it an actor" also satisfies "Making it Sendable"

Swift's classes are "reference types," but making one an actor turns it into a "reference type that manages access to its state internally." And this satisfies what Sendable implies: "values can safely be passed across concurrency domains[1]." In other words, "making it an actor" can be considered equivalent to "making it Sendable."

Also, all actors conform to the Actor protocol, and since this Actor also conforms to Sendable[2], we can confirm this.

Access from Outside an actor Requires the await Keyword

Let's also look at the difference in the code that calls Counter.increment() from the example above.

  Task.detached {
-     print(counter.increment())
+     print(await counter.increment())
  }

Because Counter was changed to an actor, calls to increment() from outside that actor now have the possibility of suspension. To indicate this, the await keyword is required when calling increment(), and using the await keyword requires an environment where concurrency is supported.

In this code example, since Counter.increment() is executed within a Task, it is in an "environment where concurrency is supported," allowing the use of the await keyword.

Wanting to make it Sendable without making it an actor

In some cases, it may not be possible to provide an "environment where concurrency is supported," and there may be patterns where the await keyword cannot be used.

However, in environments where the await keyword cannot be used, it will result in an error. So, let's change Counter back to a class instead of an actor and add conformance to Sendable.

Counter.swift
  import Foundation

- actor Counter {
+ final class Counter: Sendable {
      private var value = 0
      
      func increment() -> Int {
          value += 1
          return value
      }
  }

Then, a warning appeared: Stored property 'value' of 'Sendable'-conforming class 'Counter' is mutable.

Let's try to remove the warning by protecting this value with a lock.

Locking with OSAllocatedUnfairLock

Now, let's look at the method of locking using OSAllocatedUnfairLock.

We change value to protectedValue using OSAllocatedUnfairLock, and change the implementation of increment() to use withLock(_:).

  import Foundation
+ import os

  final class Counter: Sendable {
-     private var value = 0
+     private let protectedValue = OSAllocatedUnfairLock(initialState: 0)
      
      func increment() -> Int {
+         protectedValue.withLock { value in
              value += 1
              return value
+         }
      }
  }

This removes the var from Counter, and since protectedValue is now an OSAllocatedUnfairLock, which is Sendable, we were able to make Counter Sendable while remaining a class.

Precautions when using OSAllocatedUnfairLock

Let's look at a few more code examples using OSAllocatedUnfairLock.

In the code example in the previous section, we protected the value by putting it directly inside the OSAllocatedUnfairLock, but you can also use only the locking functionality without passing the value you want to protect to the OSAllocatedUnfairLock.

let lock = OSAllocatedUnfairLock()
lock.withLock {
    // Process that requires protection
}

There is also a method to use lock() and unlock() as a pair, without using withLock(_:).

let lock = OSAllocatedUnfairLock()
lock.lock()
// Process that requires protection
lock.unlock()

However, caution is required when using this approach. It is stated that lock() and unlock() must be called from the same thread.

When using this approach, you must call unlock() from the same thread you use to call lock().

https://developer.apple.com/documentation/os/osallocatedunfairlock

Therefore, for example, if a process that awaits is inserted between lock() and unlock() in an "environment where concurrency is supported," this method cannot be used.

❌ Do not add await processes between lock() and unlock()
let lock = OSAllocatedUnfairLock()
lock.lock()
await something()
lock.unlock()  // ❌ There is no guarantee that it is the same thread as when `lock()` was called.

In such cases, consider using an actor in the first place.

Finally, OSAllocatedUnfairLock is not a recursive lock. If a recursive lock is required, you must use NSRecursiveLock.

Using os_unfair_lock from Swift is Considered Unsafe

OSAllocatedUnfairLock is a Swift-specific object that became available in iOS 16.0+, macOS 13.0+, and others. Prior to this, there was a way to use os_unfair_lock from Objective-C. However, the documentation for OSAllocatedUnfairLock states the following:

However, it’s unsafe to use os_unfair_lock from Swift because it’s a value type and, therefore, doesn’t have a stable memory address. That means when you call os_unfair_lock_lock or os_unfair_lock_unlock and pass a lock object using the & operator, the system may lock or unlock the wrong object.

https://developer.apple.com/documentation/os/osallocatedunfairlock

However, although OSAllocatedUnfairLock is a struct, it is designed not to function as a value type, so it is said to avoid the risks mentioned above. If you have code using os_unfair_lock from Swift, let's migrate it to OSAllocatedUnfairLock.

Using NIOLock in Environments Where OSAllocatedUnfairLock Is Not Available

OSAllocatedUnfairLock is included in os and is available only on iOS 16.0+, macOS 13.0+, tvOS 16.0+, watchOS 9.0+, and visionOS 1.0+. If you want to support older environments or platforms such as Linux or Windows, you can use NIOLock from swift-nio, for example. NIOLock also conforms to Sendable.

Others

In this article, I introduced OSAllocatedUnfairLock, which is part of the os framework and not built into Swift itself (meaning import os is required). There is a proposal, SE-0433, to include this in Swift itself as Mutex[3] (as of the publication of this article, the status is Accepted).

In addition to actors and the locks mentioned in this article, there are other ways to perform "value protection," such as atomics and serial dispatch queues (like DispatchQueue).

References

脚注
  1. Refers to "values can safely be passed across concurrency domains" from the Apple Developer Documentation for Sendable. ↩︎

  2. Because AnyActor, to which Actor conforms, also conforms to Sendable. ↩︎

  3. To be precise, this is a proposal to add Mutex as a wrapper that accesses different implementations depending on the environment: os_unfair_lock on Apple platforms (Darwin), futex on Linux, SRWLOCK on Windows, and so on. ↩︎

Discussion