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

来源:互联网 发布:淘宝支付宝登录 编辑:程序博客网 时间:2024/04/29 00:20

关键代码段在很多硬件系统(比如Linux,ucOS等等)也存在,只是系统开发用于来保护现场,根据上Demo,更改如下:


#include<windows.h>
#include<iostream.h>
DWORD WINAPI FuncThreadone(LPVOID lpParameter);
DWORD WINAPI FuncThreadTwo(LPVOID lpParameter);

int index=0;
int tickets=100;
HANDLE hMutex;
HANDLE m_hEvent;
CRITICAL_SECTION g_cs;

void main(){
 HANDLE hThread1;
 HANDLE hThread2;
 hMutex=CreateMutex(NULL,0,NULL);
 m_hEvent=CreateEvent(NULL,FALSE,TRUE,NULL);

 //SetEvent(m_hEvent);

 hThread1=CreateThread(NULL,0,FuncThreadone,NULL,0,NULL);
 hThread2=CreateThread(NULL,0,FuncThreadTwo,NULL,0,NULL);
 CloseHandle(hThread1);
 CloseHandle(hThread2);
 cout<<"main thread is running"<<endl;
 //Sleep(10);
 InitializeCriticalSection(&g_cs);

 Sleep(4000);
 DeleteCriticalSection(&g_cs);
 //CloseHandle(m_hEvent);
}

DWORD WINAPI FuncThreadone(LPVOID lpParameter){

 //cout<<"thread one is running !"<<endl;
 while(1){
  //WaitForSingleObject(hMutex,INFINITE);
  //WaitForSingleObject(m_hEvent,INFINITE);
  //ResetEvent(m_hEvent);
  EnterCriticalSection(&g_cs);
  if(tickets>0){
   Sleep(1);
   cout<<"thread1 sell ticket : "<<tickets--<<endl;
   //SetEvent(m_hEvent);
   LeaveCriticalSection(&g_cs);
  }else{
   //SetEvent(m_hEvent);
   LeaveCriticalSection(&g_cs);
   break;
  }
  //ReleaseMutex(hMutex);
 }
 return 0;

}

DWORD WINAPI FuncThreadTwo(LPVOID lpParameter){

 //cout<<"thread two is running !"<<endl;
 while(1){
  //WaitForSingleObject(hMutex,INFINITE);
  //WaitForSingleObject(m_hEvent,INFINITE);
  //ResetEvent(m_hEvent);
  EnterCriticalSection(&g_cs);
  if(tickets>0){
   Sleep(1);
   cout<<"thread2 sell ticket : "<<tickets--<<endl;
   LeaveCriticalSection(&g_cs);
   //SetEvent(m_hEvent);
  }else{
   //SetEvent(m_hEvent);
   LeaveCriticalSection(&g_cs);
   break;
  }
  //ReleaseMutex(hMutex);
 }
 return 0;

}