Question

It looks like if a background thread is running when you hit the home button, things are suspended and then resumed when reopening the app. I simply want things to stop when the home button is pressed so that on resume, the user can start things from the beginning. After doing some research, it looks like a simple bool flag to periodically check is the way to go. My question, is the part after that. I have the flag part working using some of the notifications like UIApplicationWillResignActiveNotification, but my question is what action to take to actually stop things. I can do a simple return to stop things, but how does that affect the thread itself? As a general question, if nothing is running, or it gets to the end of the code, will the thread close itself? Or is some sort of explicit exit call needed? In my rough testing, that thread seems to go away, but I wasn't sure.

Was it helpful?

Solution

If you have a thread whose entry point returns, your thread will close. If you install a runloop, your thread may never close, depending on your implementation. In any case, when an app enters background, the main thread is allowed to complete the current runloop run and then the app is suspended. All other threads are suspended also. Once your app returns to the foreground, or when woken up in the background under certain circumstances, your thread will resume work until you end the entry point, suspend it or your app is suspended again.

This is a simplification, of course. In some instances, threads are reused, even if your provided entry point returns. This is the case of thread pools, GCD, etc. In these cases, a thread may appear as alive, but it is actually suspended and takes little resources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top