deimus
deimus

Reputation: 9893

iOS : Best way to organise multithreading

Guys I need some help to architect my multithreading in iOS.

I'm using ARC in my code.

So basically I need following,

In my main thread nstimer fire some method which should be executed in a separate thread, that thread does some calculation and puts data into some ivar, and another thread should read data from that ivar and do some other calculation, i.e. if there is no data the second thread should wait until there is any.

So basically I would like to hear some advice which technology is the best choice for my task, to use cocoa thread (NSThread), GCD or Operation queues.

Also can someone please provide me with some pseudo code on aspects of mutual blocking/synchronization between two threads.

Upvotes: 0

Views: 397

Answers (2)

Jody Hagins
Jody Hagins

Reputation: 28419

Unless you left something our of your problem description, that is a perfect fit for GCD/block combo. In fact, I wouldn't even use a NSTimer (GCD provides a better alternative - see dispatch_source_create for example of creating GCD based timer), but that's your call, and not what the question asked. Anyway, with GCD...

- (void)handleTimer:(NSTimer *)timer {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        __block id someObject;
        // Do work...  manipulate someObject in some manner...
        // When done, invoke other thread... main thread in this case
        dispatch_async(dispatch_get_main_queue(), ^{
            // This code is running in a different thread, and can use someObject directly
        });
    });
}

Upvotes: 0

David Rönnqvist
David Rönnqvist

Reputation: 56645

Since you are saying that some calculations should wait for other calculations to finish, I would say that you should have a look at NSOperation and set dependencies for the different operations (using addDependency).

Upvotes: 1

Related Questions