臨界段

臨界段只能用於一個進程中不同線程的通信;
與互斥量的不同體現在兩點上:
1.互斥量是內核變量,所以可以跨進程使用,當必須在進程間使用時,需要用互斥量;臨界段不是互斥變量,他是屬於進程內部的,對於進程間的通信無力;
2.臨界段用於進程間不同線程的通信效率更高,首選臨界段;

IntializeCriticalSection():創建一個臨界段;
DeleteCriticalSection():刪除一個臨界段;
EnterCriticalSection():獲取對臨界段的所有權,獨佔共享資源;
TryEnterCriticalSection():試圖獲得對臨界段的所有權,但不阻塞;
LeaveCriticalSection():釋放對資源的所有權;

在使用臨界段時,使用臨界段的進程負責爲臨界段對象分配內存。使用臨界段進行同步時,首先必須聲明一個類型爲critical
_section的全局變量,在使用該變量之前,進程中必須有一個線程調用IntializeCriticalSection()來初始化對象,後面就可以進行臨界段的其他操作了。
notice:
1.臨界段對象不能被拷貝或移動;
2.進程不能對臨界段對象進行修改;

#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;

CRITICAL_SECTION cs;

unsigned int currentID=1;

unsigned long _stdcall Mythread(LPVOID lp)
{
    int id;
    EnterCriticalSection(&cs);
    id=currentID;

    Sleep(0);
    currentID++;

    cout<<"My Identfier is:"<<id<<endl;//這個顯示輸出得放到釋放臨界段之前
    LeaveCriticalSection(&cs);
    return id;
};

int main(int argc,char*argv[])
{
  HANDLE handle;
  DWORD dw;

  InitializeCriticalSection(&cs);

  for (int i=0;i<100;i++)
  {
      handle=CreateThread(NULL,0,Mythread,NULL,0,&dw);
      CloseHandle(handle);
  }
  Sleep(60000);
  return 0;


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章