iOS併發程式設計 鎖

2021-07-09 05:07:44 字數 2153 閱讀 2440

#import 

#import 

#import 

#import 

#define iterations (1024*1024*32)

- (void

)testlock  

now = cfabsolutetimegetcurrent();  

printf("nslock: %f sec\n"

, now-then);  

then = cfabsolutetimegetcurrent();  

for(i=0;i

now = cfabsolutetimegetcurrent();  

printf("pthread_mutex: %f sec\n"

, now-then);  

then = cfabsolutetimegetcurrent();  

for(i=0;i

now = cfabsolutetimegetcurrent();  

printf("osspinlock: %f sec\n"

, now-then);  

idobj = [nsobject

new];  

then = cfabsolutetimegetcurrent();  

for(i=0;i

}  now = cfabsolutetimegetcurrent();  

printf("@synchronized: %f sec\n"

, now-then);  

}  }  

最近因為程式中頻繁使用到了鎖,不知道各種鎖對效能的影響,今天稍作測試。順便研究下裡面的機制。

測試原理:在乙個執行緒中,對空**段執行指定次數的加解鎖。算出時間差。

測試結果

可以看出來,用synchronized效率是最低的,而osspinlock效率高到無法直視。

@synchronized建立給@synchronized指令的物件是乙個用來區別保護塊的唯一標示符。如果你在兩個不同的執行緒裡面執行上述方法,每次在乙個執行緒傳遞了乙個不同的物件給anobj引數,那麼每次都將會擁有它的鎖,並持續處理,中間不被其他執行緒阻塞。然而,如果你傳遞的是同乙個物件,那麼多個執行緒中的乙個執行緒會首先獲得該鎖,而其他執行緒將會被阻塞直到第乙個執行緒完成它的臨界區。

作為一種預防措施,@synchronized塊隱式的新增乙個異常處理例程來保護**。該處理例程會在異常丟擲的時候自動的釋放互斥鎖。這意味著為了使用@synchronized指令,你必須在你的**中啟用異常處理。了如果你不想讓隱式的異常處理例程帶來額外的開銷,你應該考慮使用鎖的類。

osspinlock官方描述

spin locks are a ******, fast, thread-safe synchronization primitive that is suitable in situations

where contention is expected to be low. the spinlock operations use memory barriers to synchronize

access to shared memory protected by the lock. preemption is possible while the lock is held.

如果只是粗略的使用鎖,不考慮效能問題可以使用synchronized。

如果對效率有較高的要求,還是採用osspinlock比較好。

因為pthread的鎖在也是用osspinlock實現的。osspinlock的實現過程中,並沒有進入系統kernel,使用osspinlock可以節省系統呼叫和上下文切換。

resources

@synchronized, nslock, pthread, osspinlock showdown, done right

第四章 執行緒同步

西安 ios 開發

測試**

Java併發程式設計基礎 鎖

1 悲觀鎖和樂觀鎖 悲觀鎖 在sql語句末尾加上for update 樂觀鎖 在sql的where語句中新增version條件 update tablel set name and version 樂觀鎖並不會使用資料庫提供的鎖機制,一般在表中新增version 宇段或者使用業務 狀態來實現。樂觀鎖...

C 併發程式設計 自旋鎖

自旋鎖是指當乙個執行緒在獲取鎖的時候,如果鎖已經被其它執行緒獲取,那麼該執行緒將迴圈等待,然後不斷的判斷鎖是否能夠被成功獲取,直到獲取到鎖才會退出迴圈。include pch.h include include include include using namespace std class sp...

併發程式設計之GIL鎖

1.定義 gil global interpreter lock 全域性直譯器鎖 在cpython中,gil是乙個互斥鎖,為了防止多個本地執行緒在同一時間執行python位元組碼,因為cpython中的記憶體管理是非執行緒安全的,而cpython中的很多特性都依賴於這個特性.2.cpython直譯器...