【问题标题】:Would this recursive long polling technique result in a stack overflow?这种递归长轮询技术会导致堆栈溢出吗?
【发布时间】:2013-07-08 20:30:11
【问题描述】:

我在 pastebin 上看到了一个长轮询技术的示例,我想知道设计的递归性质是否会导致堆栈溢出?抱歉,如果这是一个菜鸟问题,但我不熟悉长轮询,我对 Objective-c 也不是很熟悉。

//long polling in objective-C
- (void) longPoll {
    //create an autorelease pool for the thread
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    //compose the request
    NSError* error = nil;
    NSURLResponse* response = nil;
    NSURL* requestUrl = [NSURL URLWithString:@"http://www.example.com/pollUrl"];
    NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];

    //send the request (will block until a response comes back)
    NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                            returningResponse:&response error:&error];

    //pass the response on to the handler 
    //(can also check for errors here, if you want)
    [self performSelectorOnMainThread:@selector(dataReceived:) 
          withObject:responseData waitUntilDone:YES];

    //clear the pool 
    [pool drain];

    //send the next poll request
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) startPoll {
    //not covered in this example:  
    // -stopping the poll
    // -ensuring that only 1 poll is active at any given time
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) dataReceived: (NSData*) theData {
    //process the response here
}

例如来源: http://pastebin.com/3z5SM4R0

【问题讨论】:

  • 它可能不会破坏堆栈,但是男孩你好,它会产生很多线程,这有时非常非常昂贵。
  • @CodaFi 所以每次递归都会产生一个新线程?
  • 这是一个实现细节。我相信如果有机会它可能会,但希望他们变得更聪明并在 GCD 之上实现它。选择器已经在后台执行,只需将其设置为延迟,它将继续在同一个线程上被调用。更好的是,将其重构为 NSOperation 并创建一个私有队列。您将能够更轻松地调试任何故障。

标签: ios objective-c http stack-overflow long-polling


【解决方案1】:

不,该代码不会导致堆栈溢出,因为每次调用都不会在当前堆栈上推送新的堆栈帧。

在 C(以及 Objective-C)中,当您调用一个函数时,“堆栈帧”被“推入堆栈”。堆栈帧包含函数调用的数据,如函数参数和返回地址(除其他外)。该信息占用空间,因此强制执行最大堆栈深度。

每次调用函数时,都会“推送”一个堆栈帧。每次函数返回时,都会“弹出”一个堆栈帧。要可视化问题,请参见以下方法:

- (void)overflow
{
     NSLog(@"Pushing...");
     [self overflow];
     NSLog(@"Popping...");
}

这将打印:

Pushing...  
Pushing...  
Pushing...  
Pushing...  
... (etc until overflow).

如您所见,函数永远不会返回。每次递归时,它都会推送另一个堆栈帧。

您发布的示例的不同之处在于该方法不直接调用自身。它使用performSelectorInBackground:withObject: 方法,它不会立即调用该方法。它将它安排在另一个线程¹(使用另一个调用堆栈)上,然后立即返回。所以,回顾一下前面的例子:

- (void)overflow
{
     NSLog(@"Pushing...");
     [self performSelectorInBackground:@selector(overflow) withObject:nil];
     NSLog(@"Popping...");
}

现在将打印:

Pushing...  
Popping...
Pushing...
Popping...
Pushing...
Popping...
... (etc forever).

因此,您可以看到第二个示例通过异步调度递归来保持平衡堆栈,而不是在自己的线程上同步调用它。


¹根据documentation

【讨论】:

  • 这有点令人困惑,但我想我明白你在说什么。那么在调用 [self performSelectorInBackground:@selector(longPoll) withObject: nil]; 时,所有这些 NS 对象都没有放在堆栈上吗?
  • 不完全是。这些对象都分配在堆上,不影响堆栈大小。我更新了更多细节。
  • 感谢马特的详细解释!
猜你喜欢
  • 2018-10-29
  • 2015-12-08
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 2011-02-26
相关资源
最近更新 更多