开发者

Is it possible to create a real nondetached (joinable) thread in iPhone OS?

开发者 https://www.devze.com 2022-12-09 08:45 出处:网络
I wonder what would happen when I create a joinable thread for writing some big data to \"disk\". Now, the docs say I can do so by using POSIX threads. Nice! But: Another guy at Apple said, that an ap

I wonder what would happen when I create a joinable thread for writing some big data to "disk". Now, the docs say I can do so by using POSIX threads. Nice! But: Another guy at Apple said, that an app has like 5 seconds or so to quit when the user presses the home button. So for my understanding a "real" nondetached thread has the sense to prevent data corruption, but when iPhone OS just kills the process after 5 seconds anyways that would not make much sense I guess.

But: Without nondetached threads, would the app quit immediately rather than getting killed after 5 seconds? Or is that just a bad myth, and a POSIX join开发者_StackOverflow社区able thread would make sure the data gets processed completely before the app quits?

Don't worry, I don't plan to make something that would prevent the user to not be able for shutting off the app. I just want to get this right.


I am not sure if using a joinable thread allows you to defer application termination until your thread is done and you join it. Probably not. You can use POSIX threads in place of NSThread or NSOperation/NSOperationQueue, but you will still have to take into account the possibility of the user terminating the application.

Now, termination may happen in one of two possible ways:

1) the app receives a SIGTERM signal that you can intercept through the applicationWillTerminate: method, which is then the SIGTERM signal handler;

2) the app receives SIGKILL: in this case you can't catch the signal through a signal handler and you are not allowed (of course) to ignore it setting the signal disposition.

If SIGTERM is the only signal sent to terminate the application, then you should be able to continue the work in your thread to save the data and exit gracefully. However, it may be that after a timeout elapses (the 5 seconds you mentioned), the app also receives SIGKILL and this event causes its immediate termination. This may be what actually happens when the user presses the home button: the iPhone OS sends SIGTERM to the app, fires a timer and when the timeout occurs it sends SIGKILL. But nothing in the documentation confirms this (or disproves it, to the best of my knowledge).

To manage this, you should do your best (application dependent of course) to save the app state atomically and as soon as possible, and you should be prepared to cancel your POSIX thread (when it reaches one of the possible cancellation points) and rollback as needed in order to cleanup before exiting.

0

精彩评论

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

关注公众号