开发者

What happens when 2 threads write to same object?

Hi there i am wondering what happens, if 2 threads writes to an object at the same time? Not sure if this should be threads, i have multiple copies of a view, each copy access and writes to a nsuserdef开发者_开发知识库ault object. What happens if two or more copies of the view writes to the same object? is there some kind of locking mechanism?

Thanks


The NSUserDefaults class is thread-safe, see the documentation. So yes, there is probably some kind of locking mechanism inside.


  1. If 2 threads write to the same object or structure without some kind of locking primitive, then very bad things will happen. At best, you'll end up with inconsistent state. At worst, your app will crash. NSUserDefaults is defined to be thread safe, so -- yes -- it is using locking of some kind.

  2. If you have views running in different threads all writing to the same object, that is indicative of a whole different problem. The UIKit isn't completely thread safe. Most UI interaction must be done from the main thread.

The docs have a bunch of information on this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜