进程同步,进程锁

1. 进程同步方式

HANDLE hMutex = CreateMutex(NULL, FALSE, "xiaoyu2");     //创建有名互斥量
  if (NULL == hMutex)
  {
   cout << "create mutex fail" << endl;
  }
  DWORD dwErrno = GetLastError();
  bool bClient = false;
  if (ERROR_ALREADY_EXISTS == dwErrno)
  {
   cout << "mutex already exist." << endl;
   CloseHandle(hMutex);
   hMutex = OpenMutex(SYNCHRONIZE, FALSE, "xiaoyu2");
   bClient = true;
  }


  while(1)
  {


   Sleep(1000);
   cout << "wait to get mutex" << endl;
   WaitForSingleObject(hMutex, INFINITE);    //一个进程获得后,在它Release之前,其他进程无法获得
   cout << "get mutex" << endl;
   int bSigned;
   cin >> bSigned;    
   ReleaseMutex(hMutex);
   cout << "releae mutex" << endl;  

}



你可能感兴趣的:(C++)