Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the stack size of iPhone fixed?

Tags:

stack

ios

iphone

When I am trying to adjust of stack size of threads:

- (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;
}

in the output, the size is not changed:

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

is the iPhone stack size fixed?

p.s. I am testing the above in iPhone 6 Plus, debug mode.

UPDATE: the stack can be adjusted when running in the Simulator on 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
like image 330
ohho Avatar asked Jun 19 '15 03:06

ohho


2 Answers

The stack size is bounded on the device, and in most cases cannot exceed 1MB for the main thread on iPhone OS, nor can it be shrunk.

The minimum allowed stack size for secondary threads is 16 KB and the stack size must be a multiple of 4 KB. The space for this memory is set aside in your process space at thread creation time, but the actual pages associated with that memory are not created until they are needed.

like image 78
Mayank Avatar answered Nov 08 '22 20:11

Mayank


Actually you can set it. I am not sure if this changed with iOS 10, but on iOS 10.2.1 this does work. The only limitation is that the stack size has to be a multiple of 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 ) ;
like image 30
István Csanády Avatar answered Nov 08 '22 19:11

István Csanády