【问题标题】:Is the stack size of iPhone fixed?iPhone的堆栈大小是固定的吗?
【发布时间】:2015-09-04 21:57:43
【问题描述】:

当我试图调整线程的堆栈大小时:

- (void)testStack:(NSInteger)n {
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(dummy) object:nil];
    NSUInteger size = 4096 * n;
    [thread setStackSize:size];
    [thread start];
}

- (void)dummy {
    NSUInteger bytes = [[NSThread currentThread] stackSize];
    NSLog(@"%@", @(bytes));
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    for (NSInteger i = 126; i <= 130; i++) {
        [self testStack:i];
    }
    return YES;
}

在输出中,大小没有改变:

2015-06-19 11:05:06.912 Stack[52982:2082454] 524288
2015-06-19 11:05:06.913 Stack[52982:2082457] 524288
2015-06-19 11:05:06.913 Stack[52982:2082456] 524288
2015-06-19 11:05:06.913 Stack[52982:2082458] 524288
2015-06-19 11:05:06.913 Stack[52982:2082455] 524288

iPhone 堆栈大小是固定的吗?

附言我正在 iPhone 6 Plus 的调试模式下测试上述内容。

更新:在 MacBook 上的模拟器中运行时可以调整堆栈:

2015-06-19 11:25:17.042 Stack[1418:427993] 528384
2015-06-19 11:25:17.042 Stack[1418:427994] 532480
2015-06-19 11:25:17.042 Stack[1418:427992] 524288
2015-06-19 11:25:17.042 Stack[1418:427991] 520192
2015-06-19 11:25:17.042 Stack[1418:427990] 516096

【问题讨论】:

  • 你为什么要增加堆栈大小?
  • 是的,我想是的......我收集了我团队的 iPhone,发现我只能将它们堆叠到几十个左右,然后它们就开始摇摇晃晃,因为背面的摄像头凸起。跨度>

标签: ios iphone stack


【解决方案1】:

堆栈大小在设备上是有限制的,在 iPhone OS 上,大多数情况下主线程不能超过 1MB,也不能收缩。

辅助线程允许的最小堆栈大小为 16 KB,堆栈大小必须是 4 KB 的倍数。此内存的空间在创建线程时在您的进程空间中留出,但与该内存关联的实际页面在需要时才创建。

【讨论】:

    【解决方案2】:

    其实你可以设置。我不确定这是否在 iOS 10 上发生了变化,但在 iOS 10.2.1 上这确实有效。唯一的限制是堆栈大小必须是 4kb 的倍数。

    pthread_attr_t tattr;
    int ret = pthread_attr_init ( &tattr ) ;
    size_t size;
    ret = pthread_attr_getstacksize(&tattr, &size);
    printf ( "Get: ret=%d,size=%zu\n" , ret , size ) ;
    
    size = 4096 * 512 ;
    ret = pthread_attr_setstacksize(&tattr, size);
    int ret2 = pthread_attr_getstacksize(&tattr, &size);
    printf ( "Set & Get: ret=%d ret2=%d,size=%zu\n" , ret , ret2 , size ) ;
    

    【讨论】:

    • 使用 NSThread API 仍然无法正常工作。只有 posix API 有效。
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2015-12-11
    • 2015-05-05
    • 2014-12-25
    • 1970-01-01
    • 2017-06-24
    相关资源
    最近更新 更多