开发者

Does OS X limit the memory usage of secondary threads?

开发者 https://www.devze.com 2023-03-31 09:04 出处:网络
I have to perform a heavy task. When I run it in the main thread, everything is perfectly fine, but when I try to run the task from a separate thread, the error which comes up is \"No memory available

I have to perform a heavy task. When I run it in the main thread, everything is perfectly fine, but when I try to run the task from a separate thread, the error which comes up is "No memory available to program now: unsafe to call malloc".

I'm using +[NSThread detachNewThreadSelector:toTarget:withObject:], and I put the required autorelease pool when necessary (t开发者_如何学Pythonhat is, at the beginning I alloc and init it, then at the end I drain it).

My question is: is there a memory limitation (maybe stack memory is cut?) on secondary threads? I have tried to debug with Instruments, however there's no leak, the app just crashes.


i don't know if this helps, but you could try using queues instead of NSThreads. link to Apple's documentation of "Migrating away from Threads" .


Looking at Apple's documentation, you can increase the stack size using -setStackSize:.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html

However, you'll have to allocate the object in order to be able to set that attribute.


The main thread has a stack of 1MB, secondary stacks has a default stack size of 512KB.

You will get this error message is you run out of stack space, and since it works on main thread but not secondary I would say that is exactly your problem.

My first advice would be to reduce recursion if you can, since 512KB is quite generous to start with, and incrementing the size will probably only post-pone your troubles. Potentially until the app is in the end users hands crashing wildly for 1-star reviews.

If you do want a bigger stack then you must instantiate, configure, and start the stack yourself. Like this:

NSThread* t = [[NSThread alloc] initWithTarget:self
                                      selector:@selector(someSelector:)
                                        object:anArgument];
[t setStackSize:1024*1024];
[t start];

The minimum stack size in 4K, and the size must by in increments of 4K.

0

精彩评论

暂无评论...
验证码 换一张
取 消