How to use Swift @MainActor and @globalActor

Actor is a new type of reference type that protects its instance data from concurrent access. Swift actors achieve this through actorisolation, which ensures (at compile time) that all access to that instance's data goes through a synchronization mechanism performed by serialization.

Actors are great for isolating instance data, providing a form of reference type that can be used in concurrent programs without introducing data races. However, when the data that needs to be isolated is scattered across the program, or represents some state that exists outside the program, it may be impractical to put all this code and data into a single actor instance (e.g., in a large program) Not even possible (when interacting with systems where these assumptions are ubiquitous).

Define global players

A global actor is a globally unique actor identified by a type. This type becomes a custom property. Any declaration can declare that it is isolated from a specific global Actor by naming the global Actor type as a property, at which point all normal Actor isolation restrictions will apply: the declaration can only be accessed synchronously from another declaration in the same on global actors, but accessible asynchronously from elsewhere.

A global Actor is a type that has the @globalActor attribute and contains a static property called shared that provides a shared instance of the Actor.

@globalActor actor UserProfileActor {
    static var shared = UserProfileActor()
}

Global actor types can be structures, enumerations, actors, or final classes. It is essentially just a token type that provides access to the actual shared participant instance via the share. A shared instance is a globally unique Actor instance that is synonymous with the global Actor type and will be used to synchronize access to any code or data annotated with the global Actor.

Global actors implicitly adhere to the GlobalActor protocol describing shared requirements. The @globalActor type is associated with GlobalActor

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/133483911