Environment Win7 flagship 64-bit system, VS2013,AMD fx™4100 Auad-core processor, 8G memory,
Look at the thread synchronization chapter of Windows core programming, and see the problem of saying that g_x++ will not sync, try to write some code to deepen the impression. Found +1 too fast, see no effect, so for loop 100 million times. The code is as follows:
#include"stdafx.h"usingStd::cout;usingStd::endl;usingstd::cin;unsigned __stdcall Threadfunrun (void* Padata)//vs Default is __cdecl call{ int*idata = (int*) Padata; for(intindex =0; Index <100000000; ++index) { (*idata) + +; } //cout << "threading Functions" << *idata << Endl; return 0;}usingStd::vector;vector<HANDLE> CreateThread (int&ivalue) {Vector<HANDLE>Vech; Const intIthrcount =2; for(intindex =0; Index < Ithrcount; ++index) {HANDLE hpt1=(HANDLE) _beginthreadex (NULL,//security_attributes 0,//cbstacksizeThreadfunrun,&Ivalue,0, NULL); Vech.push_back (HPT1); } returnVech;}BOOLWaitforrun (VectorHS) { for(intindex =0; Index < hs.size (); ++index) {DWORD Dwaitres=WaitForSingleObject (Hs[index], INFINITE); if(Dwaitres! =wait_failed) {CloseHandle (Hs[index]); } Else{cout<<"error when waiting, error ID:"<< GetLastError () <<Endl; for(; index < hs.size (); + +index) {CloseHandle (Hs[index]); } return false; } } return true;}int_tmain (intARGC, _tchar*argv[]) { Const intIcount = -; for(intindex =0; Index < icount; ++index) { intIvcalc =0; Vector<HANDLE> Hsget =CreateThread (IVCALC);//Sleep ();//cout << ivcalc << Endl; if(Waitforrun (hsget)) cout<< Ivcalc <<Endl; Elsecout<<"Section"<<index <<"The second wait thread ends an error"<<Endl; } return 0; }
The run Effects section is copied as follows:
103142316
103378991
114315655
113482883
112601936
103115533
104226349
116483624
118944471
117040062
117731078
104095516
113767825
108898288
114825927
102189580
98102943
114165950
113351409
114693549
103554014
103167647
113206459
103698422
The results are even less than 100 million.
Windows Thread Sync Learning test-1