简体   繁体   中英

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, ie 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.

由于您是说某些计算应该等待其他计算完成,因此我想说您应该查看NSOperation并为不同的操作设置依赖关系(使用addDependency)。

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
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM