Warpspace
Warpspace

Reputation: 3478

NSInvocationOperation Yield equivalent

I'm porting an Android app I made to iOS. Android has a Yield() function to move the thread from running to the back(?) of the thread queue. This is useful so that this thread doesn't hog up too much CPU and make everything else sluggish. It works well in my Android app.

I'm using NSInvocationOperation objects to implement my threads. How do I add functionality similar to Android's (POSIX's) Yield()?

Upvotes: 3

Views: 1977

Answers (4)

Tobias Kräntzer
Tobias Kräntzer

Reputation: 1714

You can use GCD for this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Do the heavy work
    // ...

    dispatch_async(dispatch_get_main_queue(), ^{

        // Reflect the result in the UI
        // ...

    });
});

Upvotes: 0

RK-
RK-

Reputation: 12219

I would suggest you to use NSOperationQueue with subclassed NSOperations. That would help.

Upvotes: 0

Kurt Revis
Kurt Revis

Reputation: 27994

I'm using NSInvocationOperation objects to implement my threads.

This doesn't make a lot of sense. NSOperations are run in a thread, but they are not threads themselves, nor would they let you implement anything equivalent to a thread. If you really want a thread, use NSThread or pthread.

How do I add functionality similar to Android's (POSIX's) Yield()?

If you really want POSIX, try sched_yield(). At a higher level, there's pthread_yield_np() (np means non-portable -- there is no pthread_yield() in POSIX) -- but that does nothing but call sched_yield().

I wouldn't bother until you find that you actually need this, and that it helps. It's not at all common to do this sort of thing in iOS or Mac apps.

Upvotes: 7

zoul
zoul

Reputation: 104145

Did you look into Grand Central Dispatch? That’s one of the best ways to write multithreaded code on iOS. (Of course, it’s not a perfect solution to all threading problems, so it depends on your app.) As an example, GCD offers you queues with lower priority for operations that aren’t performance critical.

The usual way to write a modern iOS app is to keep just the UI code on the main thread (≈ in the main GCD queue) and offload the other operations to one of the global GCD queues. Blocks from these queues don’t hog the main thread, they are offloaded to some background thread (managed by the system, not you). It’s very simple from the programmer’s point of view and it seems to work very well.

Upvotes: 1

Related Questions