Mutex可以被多次wait,那么什么情况下Wait一个Mutex才会阻塞?

asker160 2010-09-02 11:59:29
#include<windows.h>
#include<windef.h>
#include<stdio.h>
#define BUFSIZE 1024
#define NAME "mymutex"
int main(void){
HANDLE hMutex=CreateMutex(NULL,FALSE,NAME);
if(!hMutex || INVALID_HANDLE_VALUE==hMutex){
printf("CreateMutex failed\n");
return 1;
}
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,1000);
HANDLE h1=OpenMutex(SYNCHRONIZE,TRUE,NAME);
HANDLE h2=OpenMutex(SYNCHRONIZE,TRUE,NAME);
WaitForSingleObject(hMutex,1000);
CloseHandle(hMutex);
WaitForSingleObject(hMutex,1000);
return 0;
}
这个程序不会阻塞,瞬间运行完成。为什么?
我如果要让程序中的某个WaitForSingleObject()阻塞并等待,应该怎么改代码?
谢谢!!!!!
...全文
288 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxd_qd 2010-09-03
  • 打赏
  • 举报
回复
只有一个线程怎么可能阻塞?假若你真的设法把它阻塞了的话,那么再怎么解除?
asker160 2010-09-03
  • 打赏
  • 举报
回复
知道了,我用的不对:

#include<windows.h>
#include<windef.h>
#include<stdio.h>
#define BUFSIZE 1024
#define NAME "mymutex1"
HANDLE hMutex;
VOID* mythread(VOID* ){
printf("子线程等待\n");
WaitForSingleObject(hMutex,INFINITE);
printf("子线程释放\n");
ReleaseMutex(hMutex);
return 0;
}
int main(void){
hMutex=CreateMutex(NULL,TRUE,NAME);
if(!hMutex || INVALID_HANDLE_VALUE==hMutex){
printf("CreateMutex failed:%d\n",GetLastError());
return 1;
}
CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)mythread,0,0,0);
Sleep(100);//使得子线程有时间先运行
ReleaseMutex(hMutex);
printf("主线程释放\n");
BOOL ret=WaitForSingleObject(hMutex,INFINITE);
printf("主线程等待:%d\n",ret);
CloseHandle(hMutex);
return 0;
}
asker160 2010-09-03
  • 打赏
  • 举报
回复
补充一下,CreateMutex的时候,Mutex的owner指定为FALSE,当前线程不拥有。那么Mutex的属主是谁呢?

谢谢!!!!!
zgl7903 2010-09-03
  • 打赏
  • 举报
回复
看MSDN上的Mutex是用于同步不同线程的,当被其它线程所拥有时会阻塞准备获取信号量的线程
If the mutex object is owned by another thread, the wait function blocks the requesting thread until the owning thread releases the mutex object using the ReleaseMutex function

用Event

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧