C++11:互斥鎖對程式效能的影響
阿新 • • 發佈:2018-12-30
在多執行緒中,對資料的保護機制,我們用到了互斥量、臨界區、讀寫鎖、條件變數等方法。一直以來都有些擔心鎖會降低程式的效能,儘管它是必須的,但究竟它能降低多少呢?那只有靠資料說話,下面的程式碼是2個執行緒同時操作一個變數:
class TestA { public: explicit TestA() {} explicit TestA(int n) : _cnt(n) { _count = 0; _max = 0xFFFF; _tBegin = GetTickCount(); } ~TestA() {} void BeginThread() { _thrd1.SetLoopInterval(1); _thrd1._funcRunLoop = [this](void* p) { unique_lock<std::mutex> lck(_mt); if (_cnt >= _max) { _tEnd = GetTickCount(); cout << endl << "耗時:" << _tEnd - _tBegin << endl; cout << endl << "執行次數:" << _count << endl; return false; } _cnt -= 1; _count++; cout << _cnt << "\t"; return true; }; _thrd1.Start(); _thrd2.SetLoopInterval(1); _thrd2._funcRunLoop = [this](void* p) { unique_lock<std::mutex> lck(_mt); if (_cnt >= _max) { _tEnd = GetTickCount(); cout << endl << "耗時:" << _tEnd - _tBegin << endl; cout << endl << "執行次數:" << _count << endl; return false; } _cnt += 2; _count++; cout << _cnt << "\t"; return true; }; _thrd2.Start(); } void StopThread() { _thrd1.Stop(); _thrd2.Stop(); } private: int _cnt, _max, _count; DWORD _tBegin, _tEnd; std::mutex _mt; LoopThread<TestA> _thrd1; LoopThread<TestA> _thrd2; }; int main() { TestA ta(1); ta.BeginThread(); getchar(); ta.StopThread(); return 0; }
註釋:LoopThread是我封裝的一個C++11執行緒類
執行上面的程式耗時65692毫秒,如下圖所示:
注意:每次執行耗費的時間都不大相同,但差別不是很大
將執行緒中鎖去掉後(即這行程式碼:unique_lock<std::mutex> lck(_mt)),執行上述程式耗時65646毫秒,如下圖所示:
總結1:2個執行緒總共執行了大概130435~130836次,新增互斥鎖耗時(65692毫秒)-沒有互斥鎖耗時(65646毫秒)= 46毫秒,也就是說執行1000次互斥鎖大概耗時0.35毫秒,這差別微乎其微。
而且大家注意到沒,沒有加鎖的情況下,執行緒執行的次數(130836次)要比加鎖執行的次數(131053)要少,如果按照每次執行執行緒函式所耗時計算,新增互斥鎖每次執行時間:65692 / 131053 = 0.5012628478554478(毫秒/次),沒新增互斥鎖每次執行時間:65646 / 130836 = 0.5017426396404659(毫秒/次),這樣算來添加了互斥鎖每次執行的時間反而較少(當然了,輸出的資料每次都有微小的差別)。
總結2:從以上資料可以看出,C++11互斥鎖機制的效率還是很高的,幾乎不怎麼佔用時間,所以以後不用擔心鎖機制帶來的效率降低的問題了。