標籤:
環境win7旗艦64位系統,vs2013,AMD fx™4100 Auad-core processor ,8G記憶體,
看《windows核心編程》線程同步一章,看到有說g_x++會不同步的問題,試著寫些代碼加深印象。發現+1太快了,看不出效果,於是for迴圈了1億次。代碼如下:
#include "stdafx.h"using std::cout; using std::endl; using std::cin;unsigned __stdcall ThreadFunRun(void * paData)//vs預設是__cdecl 調用{ int *iData = (int*)paData; for (int index = 0; index < 100000000; ++index) { (*iData)++; } //cout <<"線程函數中"<< *iData << endl; return 0;}using std::vector;vector<HANDLE> createThread(int &ivalue){ vector<HANDLE> vecH; const int iThrCount = 2; for (int index = 0; index < iThrCount; ++index) { HANDLE hpt1 = (HANDLE)_beginthreadex( NULL,//SECURITY_ATTRIBUTES 0,//cbStackSize ThreadFunRun, &ivalue, 0, NULL ); vecH.push_back(hpt1); } return vecH;}bool waitForRun(vector<HANDLE> & hs){ for (int index = 0; index < hs.size(); ++index) { DWORD dwaitRes = WaitForSingleObject(hs[index], INFINITE); if (dwaitRes !=WAIT_FAILED) { CloseHandle(hs[index]); } else { cout << "等待時出錯,出錯ID:" << GetLastError() << endl; for (; index < hs.size();++index) { CloseHandle(hs[index]); } return false; } } return true;}int _tmain(int argc, _TCHAR* argv[]){ const int icount = 50; for (int index = 0; index < icount; ++index) { int ivCalc = 0; vector<HANDLE> hsGet = createThread(ivCalc);// Sleep(60);// cout << ivCalc << endl; if (waitForRun(hsGet)) cout << ivCalc << endl; else cout<<"第 "<<index << " 次等待線程結束出錯" << endl; } return 0; }
運行效果部分複製如下:
103142316
103378991
114315655
113482883
112601936
103115533
104226349
116483624
118944471
117040062
117731078
104095516
113767825
108898288
114825927
102189580
98102943
114165950
113351409
114693549
103554014
103167647
113206459
103698422
結果甚至有小於1億的。
windows 線程同步學習測試-1