请教一个关于互斥对象的问题(createmutex)
程序如下:
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(4000);// Sleep(10);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell tickets : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell tickets : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
我的疑惑是
线程1在释放了hMutex后,线程2就会马上获得hMutex吗?
该程序运行的结果是
thread1 sell tickets :100
thread2 sell tickets :99
thread1 sell tickets :98
thread2 sell tickets :978
....
但有没有可能出现如下的运行结果呢
thread1 sell tickets :60
thread1 sell tickets :59
thread2 sell tickets :58
thread1 sell tickets :57
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(4000);// Sleep(10);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell tickets : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell tickets : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
我的疑惑是
线程1在释放了hMutex后,线程2就会马上获得hMutex吗?
该程序运行的结果是
thread1 sell tickets :100
thread2 sell tickets :99
thread1 sell tickets :98
thread2 sell tickets :978
....
但有没有可能出现如下的运行结果呢
thread1 sell tickets :60
thread1 sell tickets :59
thread2 sell tickets :58
thread1 sell tickets :57
...全文
相关推荐
创建互斥对象禁止软件重复运行易语言模块源码-易语言.zip
创建互斥对象:使用系统提供的函数或API(如Windows API中的CreateMutex函数)创建一个互斥对象。这将返回一个标识符,后续操作都将使用这个标识符。2.
易语言创建互斥对象禁止重复运行模块
易语言创建互斥对象禁止重复运行模块"是一个解决此类问题的解决方案,尤其适用于防止同一程序在同一台计算机上多次启动的情况。
利用互斥对象实现线程同步.rar
创建互斥对象时,可以使用 CreateMutex 函数。
C++ 创建线程互斥对象
在C++编程中,线程互斥对象是多线程编程中的一个重要概念,它用于确保在任何时刻只有一个线程能够访问特定的资源或代码段,从而避免数据竞争和其他并发问题。
MutexThreadSyn_互斥对象_Vc_wheatkza_
本文将深入探讨如何在VC++环境下利用互斥对象(Mutex)来实现线程同步,以此避免竞态条件和数据不一致性的问题。


