[swift-users] DispatchQueue.async within infinite loop

Geordie J geojay at gmail.com
Wed Oct 4 13:45:43 CDT 2017


I have a somewhat unusual use-case that I’m trying to figure out.

I have a command-line swift app whose main thread ends up in an infinite loop for graphics rendering purposes (running SDL).

What I’m hoping to do is to be able to run async code like this from within that infinite loop:

DispatchQueue.someQueue.async {
	// do something
	DispatchQueue.main.async {
		// return result

The issue is that the DispatchQueue.main.async block never runs, which is pretty logical given that it’s called inside the infinite loop - so where would it possibly get to run?

The question is, how do we achieve this? Is there a better way to have an infinite loop on the main thread (e.g. Foundation’s RunLoop class etc)? On iOS (where I have the most experience with Swift), the rendering loop’s implementation is obviously hidden.

Theoretically we could probably do the entire rendering loop like this:

func renderStuff() {

	// actually render stuff

	if !shouldQuit {
		DispatchQueue.main.async(renderStuff) // loops here

// Start render loop:

But I am pretty sure the DispatchQueue API is not intended to be used like that :)

Any ideas? Maybe an API that basically says “dequeue and perform work from the DispatchQueue”?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171004/ff9e75a9/attachment.html>

More information about the swift-users mailing list