Remix.run Logo
lunacookies 5 hours ago

Author here! I’d suggest that you treat Dispatch the same way you’d treat, say, pthread_create¹ on Unix systems or CreateThread² on Windows – each platform has some features unique to it, but that doesn’t mean it’s impossible to make a cross-platform wrapper, nor does it mean that you need to restrict yourself to a lowest-common-denominator subset. In many cases it’s possible to create a cross-platform wrapper which uses platform-specific functionality where it can to suit your use-case.

Wrapping the core functionality of Dispatch I’m suggesting you use (workloops and serial queues) in a cross-platform manner isn’t difficult. On non-Apple platforms you do the standard thing: create a thread using those functions I mentioned above, have the thread sit in a loop receiving from a channel, and give the thread work to do by sending messages to the channel. On Apple platforms you’d instead create the “thread” with dispatch_workloop_create³, and you’d replace the places where you send to the channel with a call to dispatch_async⁴. Of course, this doesn’t give you any of the QoS behavior of Dispatch on non-Apple platforms, but that’s fine.

If you want to see an admittedly-complex example, WebKit’s WorkQueue⁵ is a cross-platform Dispatch wrapper.

1: https://pubs.opengroup.org/onlinepubs/9699919799.orig/functi... 2: https://learn.microsoft.com/en-us/windows/win32/api/processt... 3: https://developer.apple.com/documentation/dispatch/3191906-d... 4: https://developer.apple.com/documentation/dispatch/1452834-d... 5: https://github.com/WebKit/WebKit/blob/88039a970adb50d9cf382e...