您的位置:首页 > 编程语言

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

2013-10-24 20:33 239 查看
关键代码段在很多硬件系统(比如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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息