解釋就沒必要的驮吱,網(wǎng)上盔粹、書上太多說明了缚柏,主要說說他們的區(qū)別捉腥,和一些容易理解錯(cuò)誤的地方牧氮。
atomic并不是線程安全:
在網(wǎng)上查詢資料奠涌,大部分都會(huì)說娃殖,申明了atomic就是線程安全定庵,nonatomic就不是線程安全衰粹,屁锣光!
atomic嚴(yán)格意義上說,只是一定程度上減少了多線程讀寫錯(cuò)誤的概率铝耻,真正實(shí)現(xiàn)讀寫安全的方法誊爹,其實(shí)是在對(duì)應(yīng)屬性的set/get方法里包一層@synchroized(self){// do some thing},一個(gè)小的demo如下:
這里在set/get中包了一層synchronized(self){// do some thing}
這里為了方便瓢捉,打印了線程的名稱和對(duì)應(yīng)id的值
可以看到频丘,都是id的set方法執(zhí)行完成后的9999.
下面將@synchroized(self){ //do some thing}去掉看下
看結(jié)果
原因看文檔有說:
Using the @synchronized Directive
The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. In this case, however, you do not have to create the mutex or lock object directly. Instead, you simply use any Objective-C object as a lock token, as shown in the following example:
- (void)myMethod:(id)anObj
{
@synchronized(anObj)
{
// Everything between the braces is protected by the @synchronized directive.
}
}
The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.
As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown. This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicit exception handler, you should consider using the lock classes.
For more information about the @synchronized directive, see The Objective-C Programming Language.
參考:https://www.douban.com/note/486901956/