1 回答
TA贡献1836条经验 获得超4个赞
你的程序也太乱了吧。
Mutex的用法也很简单,在main函数里创建一个Mutex,在线程里进入一段代码前用WaitForSIngleObject,退出代码后用ReleaseMutex就行了。
下面是从static int count=5开始的程序,前面的不用改。
static int count=5;
static HANDLE h1;
static HANDLE h2;
HANDLE g_hMutex;
void func1();
void func2();
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
DWORD dwThreadID1,dwThreadID2;
g_hMutex = CreateMutex(NULL, FALSE, NULL);
h1=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
0,
(LPTHREAD_START_ROUTINE)func1,
(LPVOID)NULL,
0,&dwThreadID1);
if(h1==NULL)
printf("Thread1 create Fail!\n");
else
printf("Thread1 create Success!\n");
h2=CreateThread((LPSECURITY_ATTRIBUTES)NULL,
0,
(LPTHREAD_START_ROUTINE)func2,
(LPVOID)NULL,
0,&dwThreadID2);
if(h1==NULL)
printf("Thread2 create Fail!\n");
else
printf("Thread2 create Success!\n");
Sleep(1000);
CloseHandle(h1);
CloseHandle(h2);
ExitThread(0);
return nRetCode;
}
void func2()
{
int r2;
WaitForSingleObject(g_hMutex, INFINITE);
r2=count;
_sleep(100);
r2=r2+1;
count=r2;
printf("count in func2=%d\n",count);
ReleaseMutex(g_hMutex);
}
void func1()
{
int r1;
WaitForSingleObject(g_hMutex, INFINITE);
r1=count;
_sleep(500);
r1=r1+1;
count=r1;
printf("count in func1=%d\n",count);
ReleaseMutex(g_hMutex);
}
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
