ios – Is it safe to call DispatchObject’s methods from a background thread?


Generally mixing Swift Concurrency and GCD is a bad idea, and @lorem ipsum is correct that Task does not mean “background thread.” In many cases you should expect it to be on the same thread (since it inherits the current task context as written). That doesn’t really impact the question, though, just your example.

The answer is absolutely yes. It would be nice if I could find an explicit statement along the lines of “every Dispatch call is thread-safe unless otherwise indicated” (which is true), but I haven’t been able to find anything that broad. The closest is the statement that:

Dispatch queues themselves are thread safe. In other words, you can submit tasks to a dispatch queue from any thread on the system without first taking a lock or synchronizing access to the queue.

Also, GCD would be basically unusable for its purposes if it were not almost entirely thread-safe. In a concurrency library, you should expect the docs to call out when something is not thread-safe.

But, while I cannot find a satisfyingly universal statement in the documentation, libdispatch is open source and we can look. The function we want is _dispatch_lane_resume, and as expected, it wraps all its work in calls to os_atomic_rmw_loop2o, which is a wrapper around os_atomic_load and os_atomic_cmpxchgvw.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img