0

I need to do some synchronization with @synchronized in Obj-C and also need to sync some code in Swift using GCD.

In @synchronized we pass an object as key but what is its equivalent in GCD? It seems there isn't any way to pass key in GCD.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 1
    You can use a serial queue or actor in Swift. – cora Aug 04 '22 at 00:44
  • There is no equivalent. Generally you shouldn't use `@synchronized` in ObjC, either. Just use GCD in both cases. For more on replacing mutexes (such as `@synchronized`) with GCD, see https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW1 – Rob Napier Aug 04 '22 at 01:13
  • 1
    (BTW, `@synchronized` was created in 10.3, several years before GCD was released in 10.6. It was handy at the time, but GCD was created to get rid of the need for that kind of tool. There still are reasons to use locks rather than GCD, particularly for low-level code, but generally the right answer in that case is some form of os_unfair_lock, and in the future OSAllocatedUnfairLock, rather than a tool like `@synchronized`.) – Rob Napier Aug 04 '22 at 01:22
  • Strongly disagree with @RobNapier here. I always try to use the highest-level abstraction that gets the job done. `os_unfair_lock`, mutexes, GCD queues, etc. are all lower level abstractions than @synchronized. If all you need is to protect the value of a property in an Objective-C class, feel free to use it. If the situation is more complex, find the right tool for the job, but you haven't given us enough info to know what that would be. – ipmcc Aug 04 '22 at 16:29
  • 1
    `@synchronized` is exactly a mutex. The higher level abstraction here would be an OperationQueue rather than DispatchQueue. The link above gives a very good explanation on why Apple encourages a move towards queues (either Operation or Dispatch) over mutexes (including thin wrappers on mutexes like `@synchronized`.) When a mutex is the right tool for the job, it's because you're working at a low level. Note that all forms of queues were ported to Swift. `@synchronized` was not (which is a hint about whether it's favored...), so the answer in any case is "you can't." – Rob Napier Aug 04 '22 at 16:59
  • The same is true, for the same reasons, for the ObjC `atomic` attribute. – Rob Napier Aug 04 '22 at 17:04

0 Answers0