} ĶԡСднһ(ӽ̲ĽǶȶԽз) ˼ 1̴߳Ƶͬ 1ȣ߳ΪȺͷĻλΪӵԴĻλ 2ԣ֮ԲִУͬһ̵Ķ֮߳Ҳɲִ 3ӵԴӵԴһλ̲߳ӵϵͳԴԷڽ̵Դ. 4ϵͳڴʱϵͳҪΪ֮ͻԴϵͳĿԴڴ߳ʱĿ 2̸߳APIĹܼʹ÷ ̴߳CreateThread ߳ȼGetThreadPriority ߳ȼSetThreadPriority ж̵߳ǰǷ״̬GetExitCodeThread() ̱߳ʶGetCurrentThreadID ResumeThread ڹ̵߳ĺSuspendThread ֹ̺߳ExitThread ֹ̺߳TerminateThread()
ʵ 4_1 ߳ͬ룬۲ i ֵ #include #include #define M 90000 // ѭҪܴɶγһЩֵ int i = 0; DWORD _stdcall fun1( LPVOID p1) { } DWORD _stdcall fun2( LPVOID p1) { } int main() { DWORD id1,id2; HANDLE hThread[2]; hThread[0] = CreateThread(0,0,fun1,0,0,&id1); hThread[1] = CreateThread(0,0,fun2,0,0,&id2); WaitForMultipleObjects(2, // ȴ for( int j =0 ;j < M;j++) i--; return 0; for( int j =0 ;j < M;j++) i++; return 0; hThread, //ָ 1, //TRUEȴжFALSEһźŵִ INFINITE); //һֱȴ } cout<<\return 0; ۲iֵһΪ0ʱǺܴʱǺܴĸǶ߳ڲͬһiʱδͬʱ⡣ 4_2 ̼߳ٽͬ룬۲ i ֵӰ졣 #include #include int i; const int M=9000000; CRITICAL_SECTION cs; DWORD WINAPI fun1( LPVOID p1) { } DWORD _stdcall fun2( LPVOID p1) { } int main() { DWORD id1,id2; HANDLE hThread[2]; for( int j =0 ;j < M;j++){ } return j; EnterCriticalSection(&cs); i--; LeaveCriticalSection(&cs); for( int j =0 ;j < M;j++){ } return 0; EnterCriticalSection(&cs); i++; LeaveCriticalSection(&cs); } InitializeCriticalSection(&cs); hThread[0] = CreateThread(0,0,fun1,0,0,&id1); hThread[1] = CreateThread(0,0,fun2,0,0,&id2); WaitForMultipleObjects(2,hThread,1,INFINITE); cout<<\DeleteCriticalSection(&cs); return 0; ִУiֵ0ȷġ 4_3 û屣Դ #include #include int i=0; const int M=9000000; HANDLE hMutex; DWORD WINAPI fun1( LPVOID p1) { for( int j =0 ;j < M;j++){ WaitForSingleObject(hMutex, INFINITE) ; } DWORD _stdcall fun2( LPVOID p1) { for( int j =0 ;j < M;j++){ i++; ReleaseMutex(hMutex) ; } return 0;