2

I am trying to understand multi-threading on iOS in more detail. I went through some of the class references like NSThread, NSRunLoop, NSTask..

First of all as indicated on the following link: use of runloop

Runloop runs within a Thread.

So why do we need to define our own Runloop in our app? In the case of NSThread it is useful because some of time-consuming processes can run in a separate thread so that the app will still be responsive on the main thread.

Community
  • 1
  • 1
shebelaw
  • 3,992
  • 6
  • 35
  • 48

2 Answers2

4

Interacting with the thread's run loop may be useful if you have a thread whose work you want to continue periodically. That is, a run loop would do some work, and then when it is finished with that work, it would put the thread to rest for some time, then resume work at a later time -- effectively preventing the thread from exiting. You won't need to interact with them or configure/create them yourself regularly (only a small percentage of apps would qualify, if you are using high level abstractions such as Foundation because Foundation would set them up on your behalf in most scenarios).

If your secondary thread just does a specified task and does not need to wait for some external event (e.g. a download to finish), you would (typically) not need to interact with the run loop.

justin
  • 104,054
  • 14
  • 179
  • 226
  • 1
    Thanks; this is a much better explanation about the use of defining our own RunLoops. That was what I suspected, if I have my own thread and if I don’t define a RunLoop in that thread, the thread my exit just after it finish its task, but if I want it to hang around and may be some other task will come for it I need to define a RunLoop in it. – shebelaw Oct 18 '12 at 22:27
0

You might consider looking at using NSOperationQueues, NSOperations and NSBlockOperations instead as these will manage themselves, will allow for cancellation of tasks and can be scheduled on main and background threads.

Beltalowda
  • 4,558
  • 2
  • 25
  • 33