[swift-users] DispatchQueue.async within infinite loop

Rahul Ranjan rahul.rrixe at gmail.com
Wed Oct 4 20:07:43 CDT 2017


Hi Geordie,

I am new here and so pardon me if I misunderstood anything.

When you run a program in Swift, it already runs on main thread by default
and then you can all Dispatch async. So for example,

while true { // This while loop will run for infinite on main thread

Dispatch.main.async {} // your rendering goes here.

}

Regards,
Rahul
On Thu, 5 Oct 2017 at 2:45 AM, Geordie J via swift-users <
swift-users at swift.org> wrote:

> Hi!
>
> 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:*
> *DispatchQueue.main.async(renderStuff)*
>
> 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”?
>
> Cheers,
> Geordie
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
Rahul

Sent from iPhone
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171005/76432879/attachment.html>


More information about the swift-users mailing list