开发者

(iphone) two performSelectorInBackground share one thread?

When I call performSelectorInBackground several times, would the job be queued on same thread?

so first one be performed first and so on?

Or, 开发者_开发知识库would it run in separate thread?

Thank you


A new thread is created with each call to -performSelectorInBackground:withObject:

From http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW13

Using NSObject to Spawn a Thread

In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:

[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];

The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”


They will be executed in the same time, NOT one after the other, try this to have an idea:

-(void)prova1{
    for (int i = 1; i<=10000; i++) {
        NSLog(@"prova UNO:%i", i);
    }
}

-(void)prova2{
    for (int i = 1; i<=10000; i++) {
        NSLog(@"_________prova DUE:%i", i);
    }
}

    SEL mioMetodo = NSSelectorFromString(@"prova1");
    [self performSelectorInBackground:mioMetodo withObject:nil];
    SEL mioMetodo2 = NSSelectorFromString(@"prova2");
    [self performSelectorInBackground:mioMetodo2 withObject:nil];

you'll get:

...

___prova DUE:795

prova UNO:798

___prova DUE:796

prova UNO:799

___prova DUE:797

prova UNO:800

___prova DUE:798

prova UNO:801

___prova DUE:799

prova UNO:802

___prova DUE:800

prova UNO:803

___prova DUE:801

...

if you want a queue with 1 method after the other, try to add the 2 methods to a NSOperationQueue and set its setMaxConcurrentOperationCount to 1...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜