利用关键代码段实现多线程同步

利用关键代码段实现多线程同步

关键代码段又叫临界区,是指一个小代码段,在代码能够执行前,它必须对具有对资源的独中权。如一次只能一个人打电话的公用电话厅,开始时要建个 电话厅(初始化临界区:InitializeCriticalSection),一个人打电话(EnterCiticalSection),打完电话离 开,便于别人打(LeaveCriticalSection),电话厅不用时,拆掉,释放资源(DeleteCriticalSection);
如下程序实现多线程同步:
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI ThreadProc1(
  LPVOID lpParameter
);//define a thread function
DWORD WINAPI ThreadProc2(
  LPVOID lpParameter
);//define a thread function
int tickets=100;//the total of tickets
HANDLE g_hEvent;//define a handle of event
CRITICAL_SECTION g_cs;//define a ciritical section
int main(int argc,char** argv)
{
 HANDLE handle1;//a thread handle
 HANDLE handle2;//a thread handle
 handle1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);//create a thread
 handle2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);//creat a thread
    CloseHandle(handle1);//close a thread handle
 CloseHandle(handle2);//close a thread handle
 InitializeCriticalSection(&g_cs);
    Sleep(4000);
    DeleteCriticalSection(&g_cs);
 return 0;
}
DWORD WINAPI ThreadProc1(
  LPVOID lpParameter
)
{
   while(TRUE)
   {
    EnterCriticalSection(&g_cs);
    if(tickets>0)
    {
     Sleep(2);
     cout<<"Thread1 Ticket:"<<tickets--<<endl;
    
    }
    else
     break;
    LeaveCriticalSection(&g_cs);
   }
     
 return 0;
}
DWORD WINAPI ThreadProc2(
  LPVOID lpParameter
)
{
 while(TRUE)
   {
   EnterCriticalSection(&g_cs);
    if(tickets>0)
    { 
     Sleep(2);
     cout<<"Thread2 Ticket:"<<tickets--<<endl;
    
    }
    else
     break;
    LeaveCriticalSection(&g_cs);
   }
 return 0;
}


WINAPI是函数调用的一种约定,等同于__stdcall,该调用约定规定,按从右至左的顺序压参数入栈,由被调用者把参数弹出栈!

posted @ 2009-08-28 18:42  dzqabc  阅读(352)  评论(0编辑  收藏  举报