简体   繁体   English

iOS:组织多线程的最佳方法

[英]iOS : Best way to organise multithreading

Guys I need some help to architect my multithreading in iOS. 伙计们,我需要一些帮助来构建我在iOS中的多线程。

I'm using ARC in my code. 我在代码中使用ARC。

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. 在我的主线程nstimer fire中,应在单独的线程中执行某些方法,该线程进行一些计算并将数据放入某个ivar,另一个线程应从该ivar读取数据并进行其他计算,即如果没有数据第二个线程应该等待,直到有任何线程。

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. 因此,基本上我想听听一些建议,使用可可线程(NSThread),GCD或Operation队列是哪种技术最适合我的任务。

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. 除非您留下问题描述的内容,否则它非常适合GCD /块组合。 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. 实际上,我什至不使用NSTimer(GCD提供了更好的替代方法-例如,有关创建基于GCD的计时器的信息,请参阅dispatch_source_create),但这只是您的电话,而不是问题的所在。 Anyway, with GCD... 无论如何,有了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
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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