windows编程---临界区对象

(2010-08-25 09:45:35)
转载
标签:

windows内核

临界区

代码

杂谈

分类: Windows

#include <iostream.h>
#include <windows.h>

int tickets = 100;
CRITICAL_SECTION g_cs;

DWORD WINAPI fThread1(LPVOID lpParameter)
{
 while(TRUE)
 {
  EnterCriticalSection(&g_cs);
  if(tickets > 0)
  {
   Sleep(1);
   cout<<"fThread1 sell: "<<tickets--<<endl;
  }
  else
  {
   break;
  }
  LeaveCriticalSection(&g_cs);
 }
 return 0;
}

DWORD WINAPI fThread2(LPVOID lpParameter)
{
 while(TRUE)
 {
  EnterCriticalSection(&g_cs);
  if(tickets > 0)
  {
   Sleep(1);
   cout<<"fThread2 sell: "<<tickets--<<endl;
  }
  else
  {
   break;
  }
  LeaveCriticalSection(&g_cs);
 }
 return 0;
}

int main()
{
 HANDLE hThread1;
 HANDLE hThread2;
 hThread1 = CreateThread(NULL,0,fThread1,NULL,0,NULL);
 hThread2 = CreateThread(NULL,0,fThread2,NULL,0,NULL);
 CloseHandle(hThread1);
 CloseHandle(hThread2);
 InitializeCriticalSection(&g_cs);
 Sleep(4000);
 DeleteCriticalSection(&g_cs);
 return 0;
}

你可能感兴趣的:(编程,windows,null,2010,winapi)