利用關鍵程式碼片段實現多線程同步

來源:互聯網
上載者:User

利用關鍵程式碼片段實現多線程同步

關鍵程式碼片段又叫臨界區,是指一個小程式碼片段,在代碼能夠執行前,它必須對具有對資源的獨中權。如一次只能一個人打電話的公用電話廳,開始時要建個
電話廳(初始化臨界區: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 functionint 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,該呼叫慣例規定,按從右至左的順序壓參數入棧,由被調用者把參數彈出棧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.