Reputation: 1478
I use some global variables, only Integer, which can be accessed from several threads. Under normal circumstances only one thread writes this variable but other threads read them.
var xxx: Integer = 0
What must be done to make this variable thread-safe for Swift 6?
Can somebody give me a simple example, how to handle my few global variables. The variables are currently not part of a class/struct. Only simple variables.
Upvotes: 3
Views: 426
Reputation: 273540
From SE-0412,
Under strict concurrency checking, require every global variable to either be isolated to a global actor or be both:
- immutable
- of
Sendable
type
Since your variable must be a var
, it must be isolated to a global actor. You can use an existing global actor like @MainActor
:
@MainActor
var x = 0
Or write your own global actor
@globalActor
public struct SomeGlobalActor {
public actor MyActor { }
public static let shared = MyActor()
}
@SomeGlobalActor
var x = 0
In either case, you would need an await
to access this from a context not isolated to the global actor.
Finally, if you want to synchronise access to this global variable in your own way, you can do:
nonisolated(unsafe) var x = 0
This gives up the compile-time thread-safety checks that Swift does for you.
Upvotes: 3