臨界區(qū)
#include "stdafx.h"
#include <windows.h>
int total = 100;
CRITICAL_SECTION cs;
DWORD WINAPI test1(LPVOID param)
{
bool isRun = true;
while(isRun)
{
EnterCriticalSection(&cs);
if(total>0)
{
printf("線程test1工作中=====還剩%d張票\n",total);
total--;
printf("賣出一張烙如,還剩%d張票\n",total);
}
else
{
isRun = false;
}
LeaveCriticalSection(&cs);
}
return 0;
}
DWORD WINAPI test2(LPVOID param)
{
bool isRun = true;
while(isRun)
{
EnterCriticalSection(&cs);
if(total>0)
{
printf("線程test2工作中=====還剩%d張票\n",total);
total--;
printf("賣出一張你弦,還剩%d張票\n",total);
}
else
{
isRun = false;
}
LeaveCriticalSection(&cs);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread[2];
InitializeCriticalSection(&cs);
hThread[0] = CreateThread(NULL,0,test1,NULL,0,NULL);
hThread[1] = CreateThread(NULL,0,test2,NULL,0,NULL);
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
printf("Hello World!\n");
return 0;
}
互斥體
#include "stdafx.h"
#include "windows.h"
int main(int argc, char* argv[])
{
//創(chuàng)建互斥體
HANDLE m_hMutex = CreateMutex(NULL,FALSE,"cplusplus_me");
/*
m_hMutex創(chuàng)建成功返回句柄招拙,如果已經(jīng)存在返回已經(jīng)存在的句柄前联,
GetLastError 返回 ERROR_ALREADY_EXISTS
*/
WaitForSingleObject(m_hMutex,INFINITE);//獲取令牌
DWORD dwRet = GetLastError();
if (m_hMutex)
{
if (ERROR_ALREADY_EXISTS == dwRet)//防止多開的一種手段
{
printf("程序已經(jīng)在運行中了,程序退出!\n");
CloseHandle(m_hMutex);
return 0;
}
}
else
{
printf("創(chuàng)建互斥量錯誤,程序退出!\n");
CloseHandle(m_hMutex);
return 0;
}
while(1)
{
printf("cplusplus_me\n");
}
ReleaseMutex(m_hMutex);//釋放令牌
CloseHandle(m_hMutex);
return 0;
}
想知道CreateMutex的第二個參數(shù)的朋友,自己查下文檔僚楞。