【问题标题】:Multithreading with NSThread使用 NSThread 进行多线程
【发布时间】:2012-12-08 22:21:49
【问题描述】:

我是新手,如有错误请见谅...

我的情况:

- (id)initWith... //Some arguments

有一个返回对象的初始化方法。用参数的值设置它的实例变量做了很多工作。为了最大限度地提高性能,我将工作分成两个线程。一个线程设置一组相关变量,另一个线程设置另一组变量。

- (id)initWith:arguments {
self = [super init];
if (self) {
[NSThread detachNewThreadSelector:@selector(setFirstSetOfVariables:) toTarget:self withObject:argObject];
[self setSecondSetOfVariables:arguments];
//Check if the thread finished its work and return the value
return self;
}

为方便起见,请认为该方法必须设置的两组 var 没有任何关系。那么我的问题是:如何检查第一个线程是否完成?我可以创建一个 BOOL var,但我必须创建一个循环来检查。我也可以调用一个方法来表示它已经准备好了。但由于我不太了解,我不知道在线程内部调用的方法是在主线程中运行还是在另一个线程中运行。对不起。感谢您提供任何信息。

【问题讨论】:

  • 有什么原因,你在init方法中做了这么多工作。我认为创建对象然后在对象上调用另一个方法来创建所有其他值会更好。我建议您阅读有关 GCD 或其他执行后台作业的简单方法的信息。甚至 Apple 也建议不要使用 NSThread 类,甚至在其并发编程指南中也将 NSThread 的讨论降级。
  • @Srikanth 说了什么;通常不鼓励使用 NSThread。也不鼓励在 init 中进行重量级初始化。您确实希望构建您的应用程序,以便您可以将“设置我的所有对象”与“OK,GO!”分开。

标签: iphone objective-c multithreading cocoa nsthread


【解决方案1】:

你可以这样做来简化整个事情

ComplicatedObject *myComplicatedObject = [ComplicatedObject alloc] init;

[myComplicatedObject setLongTimeTakingVariables];

并在 ComplicatedObject 中创建一个类似的方法

-(void)setLongTimeTakingVariables{
  dispatch_async(dispatch_get_global_queue(),^{ All of your code can go here. Infact you need not split it into two sections, because it will happen in the background and your userinterface will not get affected }

但如果你想拆分,那么你可以这样做

   dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),^{  
                   some work here
     }

    dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),'{
                    some other work here
    }

阅读并发编程指南,每件事都解释得很清楚。

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2023-04-05
    • 1970-01-01
    • 2011-11-20
    • 2015-09-26
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多