gpt4 book ai didi

ios - 这种递归长轮询技术会导致堆栈溢出吗?

转载 作者:可可西里 更新时间:2023-11-01 16:52:12 27 4
gpt4 key购买 nike

我在 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

最佳答案

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

在 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

关于ios - 这种递归长轮询技术会导致堆栈溢出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com