3

次のコードは、NSOperationQueue に複数の NSOperation インスタンスを追加します。Operation は URL のコンテンツを取得するだけです。私もphpコードを提供しています...

次のコードを考えると...

-(void)requestResponse {

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.someurl.gr/test.php"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:40.0];

    NSDate *dd = [NSDate date];

    NSURLResponse *resp;
    NSData *returnedData = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:NULL];

    NSString *ss = [[[NSString alloc] initWithData:returnedData encoding:NSUTF8StringEncoding] autorelease];

    NSLog(@"%@ - %.2f",ss , -[dd timeIntervalSinceNow]);

}


-(NSOperation*)task {
    NSInvocationOperation* theOp = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(requestResponse) object:nil] autorelease];
    return theOp;
}


-(IBAction)buttonAction:(id)sender {

    NSOperationQueue *opq = [[NSOperationQueue alloc] init];
    [opq setMaxConcurrentOperationCount:40];

    for(int i=0; i<15;i++) {
        [opq addOperation:[self task]];
        [NSThread sleepForTimeInterval:1.0]; // here is the issue!
    }

    [opq release];
}

test.php witch -requestResponse 呼び出しの内容:

<?php
    echo "Through!";
    for($i=0;$i<1000000;$i++) { // don't return too soon
    }
?>

問題は[NSThread sleepForTimeInterval:1.0]、キューに NSOperation を追加する前に遅延を作成するために使用すると、すべての要求が完了するまでにほぼ同じ時間がかかることです。この行にコメントすると、ほとんどのリクエストが完了するまでにかなりの時間がかかります。問題はなぜですか?

コマンドラインから(curlを使用して)URLをテストしましたが、phpへの同時呼び出しの数に関係なく、要求が完了するまでに同じ時間がかかるため、問題はサーバー側ではありません。

これは、 sleepForTimeInterval が無効になっているサーバーとして localhost を使用した出力です。

[s] Through! - 0.22
[s] Through! - 0.23
[s] Through! - 0.25
[s] Through! - 0.26
[s] Through! - 0.26
[s] Through! - 0.28
[s] Through! - 0.43
[s] Through! - 0.46
[s] Through! - 0.49
[s] Through! - 0.50
[s] Through! - 0.52
[s] Through! - 0.51
[s] Through! - 0.60
[s] Through! - 0.62
[s] Through! - 0.63

// もちろん、PHP が実際の作業を行っている場合、違いははるかに大きくなります (7 秒から 20 秒まで!)。

およびsleepForTimeInterval が有効になっている

[s] Through! - 0.23
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.08
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.08
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
4

1 に答える 1

0

sleepForTimeIntervalを有効にすると、NSOperation が完了するまでに時間がかかります。したがって、一度に実行される同時操作は 1 つだけです。

sleepForTimeIntervalを無効にすると、完了すべき複数の並列操作を NSOperationQueue に提示することになります。

何に[NSoperationQueue setMaxConcurrentOperationCount]設定していますか?すべての操作を並行して完了できるように、必ず 15 に設定します。おそらく、現時点では操作がキューに入っているため、すべてが並行して実行されているわけではないと考えています。

于 2011-04-25T16:00:58.590 に答える