用 临界区 函数实现 互斥
open/createMutex 区别
https://www.cnblogs.com/staring-hxs/p/3664765.html
互斥详解
https://blog.csdn.net/morewindows/article/details/7481609
#include <iostream>
#include <windows.h>
using namespace std;
static HANDLE hHandle1,hHandle2= NULL;
DWORD h1,h2;//用于存储线程标识符的变量
LPCRITICAL_SECTION lpCriticalSection;//临界区指针
void func1();
void func2();
int count=0;
CRITICAL_SECTION Critical; //定义临界区
int main()
{
//thread1
hHandle1 = CreateThread( (LPSECURITY_ATTRIBUTES) NULL,0,(LPTHREAD_START_ROUTINE) func1,(LPVOID) NULL,0, &h1 );
//thread2
hHandle2 = CreateThread( (LPSECURITY_ATTRIBUTES) NULL,0,(LPTHREAD_START_ROUTINE) func2,(LPVOID) NULL,0, &h2 );
lpCriticalSection=& Critical;
InitializeCriticalSection( lpCriticalSection);//初始化临界区
//两个及以上必须这么写
HANDLE hThread[2] = {0};
hThread[0]=hHandle1;
hThread[1]=hHandle2;
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
CloseHandle(hHandle1);
CloseHandle(hHandle2);
DeleteCriticalSection(lpCriticalSection);//删除临界区
ExitThread(0);//撤销主线程
return 0;
}
void func1()
{
EnterCriticalSection(lpCriticalSection);//进入临界区 —— 相当于p(mutex)
count++;
while(count<10)
{
printf("in_fun2\n");
count++;
}
printf("2:%d\n",count);
LeaveCriticalSection(lpCriticalSection);//退出临界区 ——相当于v(mutex)
}
void func2()
{
EnterCriticalSection(lpCriticalSection);//进入临界区 —— 相当于p(mutex)
count++;
while(count<10)
{
printf("in_fun2\n");
count++;
}
printf("2:%d\n",count);
LeaveCriticalSection(lpCriticalSection);//退出临界区 ——相当于v(mutex)
}
用mutex实现
#include <iostream>
#include <windows.h>
using namespace std;
static HANDLE hHandle1,hHandle2,hMutex= NULL;
DWORD h1,h2;//用于存储线程标识符的变量
void func1();
void func2();
int count=0;
int main()
{
//thread1
hHandle1 = CreateThread( (LPSECURITY_ATTRIBUTES) NULL,0,(LPTHREAD_START_ROUTINE) func1,(LPVOID) NULL,0, &h1 );
//thread2
hHandle2 = CreateThread( (LPSECURITY_ATTRIBUTES) NULL,0,(LPTHREAD_START_ROUTINE) func2,(LPVOID) NULL,0, &h2 );
hMutex = CreateMutex(NULL, FALSE, "m1");
HANDLE hThread[2] = {0};
hThread[0]=hHandle1;
hThread[1]=hHandle2;
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
CloseHandle(hHandle1);
CloseHandle(hHandle2);
CloseHandle(hMutex);
ExitThread(0);//撤销主线程
return 0;
}
void func1()
{
WaitForSingleObject(hMutex, INFINITE);
count++;
while(count<10)
{
printf("in_fun1\n");
count++;
}
printf("1:%d\n",count);
ReleaseMutex(hMutex);
}
void func2()
{
WaitForSingleObject(hMutex, INFINITE);
count++;
while(count<10)
{
printf("in_fun2\n");
count++;
}
printf("2:%d\n",count);
ReleaseMutex(hMutex);
}