calling performSelectorInBackground: from background thread

社会主义新天地 提交于 2019-12-07 12:19:48

问题


What is the real effect of calling performSelectorInBackground:... from a method that is running in the background? I want it to run asynchronously

For example:

- (void) _imageBufferWasUpdated{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //do something here

    if(shouldContinue){ 
        [self performSelectorInBackground:@selector(_loop) withObject:nil];
    }
    [pool release];
}

_imageBufferWasUpdated will run in the background and I want to call _loop method asynchronously (in the background also so _imageBufferWasUpdated will finish soon, probably before _loop ends).

Is this correct?

Is there a more efficient (and relatively simple) way to do this using GCD? I would appreciate it if you could give some example on how to fork this using GCD. I think I need at least 3 threads, Main thread, background thread for running _imageBufferWasUpdated and other background thread for _loop. Am I correct?

Thanks in advance Ignacio


回答1:


What you are doing seems fine to me. Cocoa probably uses a single background thread, so it should not lead to excessive thread creation.

If you want more control, you could use NSOperation or GCD. Both are quite simple. Eg, GCD would be like this

#import <dispatch/dispatch.h>

...

dispatch_async( dispatch_get_global_queue(0,0), ^{
    [self _loop];
}];



回答2:


performSelectorInBackground forks your selector to a background thread. [documentation]

I don't know if I'm right, but you should do everything using GCD or its high level classes (NSOperationQueue). Forking too many background threads might cause a decrease in performance if the system is saturated with too many threads and have not enough computing resources

GCD automatically manages how many threads operate concurrently based upon available system resources.



来源:https://stackoverflow.com/questions/4422561/calling-performselectorinbackground-from-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!