iPhone单例对象同步

发布于 2024-09-02 23:11:09 字数 244 浏览 5 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔一刀 2024-09-09 23:11:09

基本上,如果数据被修改,您只需要担心同步(即使只有一个“线程”修改它,其余的仅读取它)。如果一个或多个线程确实修改了单例中的数据(或单例引用的任何数据),那么您需要某种算法来处理数据争用(初学者应该坚持基于“锁”的算法)。对于多线程共享的所有数据都是如此,而不仅仅是单例。

函数与问题无关(尽管函数经常会更改数据,并且同一函数在多个线程上调用时会更改相同的数据并读取相同的数据)。如果该函数是“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).

夜司空 2024-09-09 23:11:09

单例并不能解决多线程访问的问题。

根据数据的性质及其更新方式,您可能需要使用某种锁定机制来保护它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文