wait for other thread to finish in objective c

2.3k views Asked by At

I am using MGTwitterEngine to fetch tweets from twitter. This uses a asynchrounous paradigm to fetch that tweetsin another thread. It returns the fetched results to the main thread.

Because I have some processing todo after the tweets are fetched, I would like to introduce another thread to prevent locking the UI thread. I would lik to do it this way: UI thread starts a new thread X. thread X starts the asynchronous fetching of tweets with MGTEngine, and waits for that to finish. When MGTwitterEngine returns, thread X processes the tweets, and notifies the UI thread that we are ready.

My question is: How to set thread X to wait till MGTwitterEngine is reade?

2

There are 2 answers

1
Luke Mcneice On BEST ANSWER

There is very little excuses not to use multithreading with blocks now. They are quicker to develop than NSOperations, synchronisation is simpler, jumping threads (e.g. grabbing the UI thread) is simpler and in my own experience it performance is better.

In this case, I would create a block, spawn a new thread to fire up your async fetch (possibly spawning an async fetch for each one- makes cancelations easier) put 2 sync blocks in the queue that will fire after the fetches are done for the processing and the UI update. Here is a good tut: http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/

//GOES IN Tweet delegate

myQueue = dispatch_queue_create("myQueue", 0);//local instance var dispatch_queue_t

dispatch_async(myQueue, ^{

                      [self processTweets];//executed after fetch is done.
                      dispatch_sync(dispatch_get_main_queue(), ^{
                          [self uiBasedFunction];//executed on main thread
                                                            });
                         });
dispatch_release(myQueue);
0
Girish Kolari On

There are 2 ways you can do this.

  1. Use blocking netwrok calls --- if posible.

  2. Call CFRunLoopRun() --- to wait for another event to proceed with the operation in the thread. Once a asynchronous data fetching is done call CFRunLoopStop() on X runloops context in thread x.