New GCD API: DispatchWorkItem.current like Thread.current

Hi,

I’d like to propose a change to add a new GCD API, so we can use DispatchWorkItem more like to Thread.

open class DispatchWorkItem {
    public class var current: DispatchWorkItem? { get }
}

This makes using it in concurrent DispatchQueue similar to using Thread directly.

What do you think?

Unfortunately GCD doesn't fall under the Swift Evolution process so proposing features here doesn't do much but prompt some discussion. If you'd like to suggest improvements to the API you should file Feedback with Apple.

2 Likes

As Jon said, this isn't really the purview of Swift Evolution. :frowning:

For what it's worth… this API is intentionally excluded from GCD in Swift and is deprecated in Objective-C.

This function is unavailable/deprecated because it is not possible to correctly reason about the state of your program based on this function's result. Multiple queues can be bound to the same thread at the same time, and code executing on one of those queues is in fact executing on all of them. For example, if queue A synchronously dispatches a work item to queue B, the work item usually executes on the same thread as the caller, and for the duration of that work item the thread is bound to both queues.

Instead of trying to determine the current queue, model your code such that you don't need to know that information. If you want to assert that you're operating on a particular queue, there is API in GCD that lets you do so. If you want to execute a callback on the calling queue, let your caller specify a queue instead.

I hope that helps!