lockFunctionDemo

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<process.h>
 4 #include<windows.h>
 5
 6 int g_nCount1 = 0,g_nCount2 = 0;
 7 bool g_bThread = true;
 8 UINT __stdcall ThreadProc(LPVOID);
 9 int main(int argc,char* argv[])
10 {
11     HANDLE h[2];
12     unsigned m_uThreadId;
13     h[0] = (HANDLE)::_beginthreadex(NULL,0,ThreadProc,NULL,0,&m_uThreadId);
14     h[1] = (HANDLE)::_beginthreadex(NULL,0,ThreadProc,NULL,0,&m_uThreadId);
15     Sleep(1000);
16     g_bThread = false;
17     ::WaitForMultipleObjects(2,h,true,INFINITE);
18     printf("g_nCount1: %d   g_nCount2: %d\n",g_nCount1,g_nCount2);
19     ::CloseHandle(h[0]);
20     ::CloseHandle(h[1]);
21
22     system("pause");
23     return 0;
24 }
25 UINT __stdcall ThreadProc(LPVOID lpParam)
26 {
27     while(g_bThread)
28     {
29         InterlockedIncrement((long*)&g_nCount1);
30         InterlockedDecrement((long*)&g_nCount2);
31     }
32     return 0;
33 }
时间: 2024-12-13 11:13:21

lockFunctionDemo的相关文章