Objective-C 2.0中的多线程问题 [英] Multi-Threading question in Objective-C 2.0

查看:106
本文介绍了Objective-C 2.0中的多线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的主要应用程序委托,它包含一个返回对象的方法。这个应用程序委托在主线程上运行。

I have my main application delegate which contains a method that returns an object. This application delegate runs on the main thread.

我也有一个NSOperation运行在不同的线程。除了想要能够在我的主线程上调用我的应用程序委托方法有时,我还需要从我的NSOperation线程调用它来获取它返回的对象。我的第一个问题是,如果我从我的其他线程调用它...

I also have a NSOperation that gets run on a different thread. As well as wanting to be able to call my app delegate method on my main thread sometimes, I also need to call it from my NSOperation thread to get the object that it returns. My first question is, if I call this from my other thread...

id newObject = [[[UIApplication sharedApplication] delegate] myMethod];

...该方法将在与NSOperation相同的线程上处理,

... will that method be processed on the same thread as the NSOperation, or will it be the same thread (main) as the application delegate is on?

我还想确保 myMethod 只能通过我的操作线程或我的主线程一次调用一次。我可以在我的应用程序委托中创建一个NSLock实例var,并执行类似的操作:

I also want to make sure that the code within myMethod is only called once at a time by either my operation thread or my main thread. Can I just create a NSLock instance var in my application delegate and do something like:

-(id)myMethod {
    [myLock lock];
    myObject = // Get or create my object to return
    [myLock unlock];
    return myObject;
}

感谢您的帮助!

Mike

推荐答案

除非你明确地编写代码来在另一个线程上执行,否则每个方法调用都会直接在被调用的线程上执行。方法调用没有魔法。您可以将其视为与用于线程的C函数调用具有完全相同的语义/ ABI。

Unless you explicitly write code to cause something to execute on another thread, every method call is going to be executed directly on the thread it was called upon. There is no magic with a method call. You can think of it as having the exact same semantics/ABI as a C function call for the purposes of threading.

您的锁定模式将正常工作,

Your locking pattern will work fine to ensure exclusive access across threads.

两个额外的不相关的笔记(因为这么多人浏览它):

Two additional unrelated notes (because so many people trip over it):


  • 声明属性 atomic 与线程安全无关。原子性只保证您获得有效的值,而不是正确的值(有区别)。

  • declaring a property as atomic has little to do with thread safety. Atomicity only guarantees that you get a valid value, not the correct value (there is a difference).

自动释放的对象永远不会安全地在线程之间传递。您需要在发送线程上显式的 retain ,并在接收线程上创建一个平衡的 release

autoreleased objects are never safe to pass between threads. You need an explicit retain on the sending thread and a balancing eventual release on the receiving thread.

这篇关于Objective-C 2.0中的多线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆