NSOperationQueue does not reuse stream on iPhone

I am using the iPhone SDK 3.1.2, and the following code shows that NSOperationQueue is not reusing a thread for each task.

The code has no problems with Snow Leopard.

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after app launch    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    for(int i = 0; i < 100; i++) {
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
        [queue addOperation:op];
        [op release];
    }
}

- (void)run {
    static int tc = 0;
    if([[NSThread currentThread] isMainThread]) {
        NSLog(@"MAIN THREAD");
        return;
    } else if([[NSThread currentThread] name] == nil) {
        [[NSThread currentThread] setName:[NSString stringWithFormat:@"THREAD_%d", tc++]];
    }
    NSLog(@"%@", [[NSThread currentThread] name]);
}

The result shows that it creates 100 threads to complete 100 tasks.

2010-01-07 11:46:03.502 OperationQueueTest[7911:4503] THREAD_0
2010-01-07 11:46:03.506 OperationQueueTest[7911:4d03] THREAD_1
2010-01-07 11:46:03.507 OperationQueueTest[7911:4807] THREAD_2
2010-01-07 11:46:03.510 OperationQueueTest[7911:4d07] THREAD_3
2010-01-07 11:46:03.514 OperationQueueTest[7911:5007] THREAD_4
2010-01-07 11:46:03.516 OperationQueueTest[7911:4f0b] THREAD_5
2010-01-07 11:46:03.518 OperationQueueTest[7911:4e0f] THREAD_6
...
2010-01-07 11:46:03.740 OperationQueueTest[7911:4ea7] THREAD_97
2010-01-07 11:46:03.744 OperationQueueTest[7911:4dcf] THREAD_98
2010-01-07 11:46:03.746 OperationQueueTest[7911:460f] THREAD_99
+5
source share
3 answers

NSOperationQueue is for combining and reusing streams in the most efficient way, in which case it seems that the decision to reuse streams was the best way.

( , , , , NSOperationQueue ), , NSOperationQueue ; .

, , , , , . .

, , NSStrings, , , - , NSInvocationOperation.

+9

Snow Leopard NSOperation/NSOperationQueue GCD.

iPhone - Leopard. , ( ).

, , NSOperationQueue.

+2

NSOperationQueue ( ). , , , .

NSOperation, NSOperationQueue, , .

- (void)operaitonqueueTest
{

    _opQueue = [[NSOperationQueue alloc] init];
    [_opQueue setMaxConcurrentOperationCount:5];
    for(int i = 0; i < 50; i++) {
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
        [_opQueue addOperation:op];
    }
}

- (void)run {
    if([[NSThread currentThread] isMainThread]) {
        NSLog(@"MAIN THREAD");
        return;
    }
    NSLog(@"currentThread = %@", [NSThread currentThread]);
}
0

All Articles