iPhone单例对象同步
我正在开发一个 iPhone 应用程序,但这可能是一个普遍问题。
我有一个单例模型类,并且在某些情况下会存在多个 NSOperations(线程)并与单例对象一起使用。如果它们都在这个对象中调用相同的方法,我是否需要一些锁定机制?
或者这个方法一次只能执行一个吗?
我没有计算机科学背景,但我的猜测是所有线程都会调用相同的地址(此方法)。另外,您能否推荐一本讨论一般编程概念的优秀初学者编程书籍。我没有头脑去读高德纳之类的书。
I'm working on an iphone app but this is probably a general question.
I have a singleton Model class and there would be scenarios where multiple NSOperations (threads) would exist and work with the singleton object. If they all call the same method in this object, do i need to have some locking mechanism?
Or can this method be executed only one at a time?
I do not have a computer science background but my guess is that all threads would have their CALL to the same address (this method). Also can you please suggest a good beginner programming book that discusses general programming concepts. I don't have the brains for Knuth kinda books.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,如果数据被修改,您只需要担心同步(即使只有一个“线程”修改它,其余的仅读取它)。如果一个或多个线程确实修改了单例中的数据(或单例引用的任何数据),那么您需要某种算法来处理数据争用(初学者应该坚持基于“锁”的算法)。对于多线程共享的所有数据都是如此,而不仅仅是单例。
函数与问题无关(尽管函数经常会更改数据,并且同一函数在多个线程上调用时会更改相同的数据并读取相同的数据)。如果该函数是“const”函数(即不能/不会修改任何数据,那么在多个线程上调用是安全的,只要没有其他东西触及该函数读取的数据)。
Basically you only need to worry about synchronisation if data is MODIFIED (even if only one "thread" modifies it and the rest only read it). If one or more threads do modify the data in the singleton (or any data the singleton refers to), then you need some sort of algorithm to deal with the data contention (beginers should stick to "lock" based algorthims). This is true of all data shared by multiple threads, not just singletons.
Functions have nothing to do with the problem (though functions will often change data and the same function will change the same data and read the same when called on multiple threads). If the function is a 'const' function (i.e. can't/won't modify any data, then it is safe to call on multiple threads, so long as nothing else touches the data that function reads).
单例并不能解决多线程访问的问题。
根据数据的性质及其更新方式,您可能需要使用某种锁定机制来保护它。
Having a singleton does not solve the problems of access from multiple threads.
Depending on the nature of your data and how it's updated, you may likely need to protect it with some sort of locking mechanism.