互斥量
来源:互联网 发布:寻梦环游记 知乎 编辑:程序博客网 时间:2024/05/21 06:56
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName);
1:lpMutexAttributes应该设为NULL
2:bInitialOwner指定调用线程是否立刻拥有刚刚创建线程的互斥量的所有权
3:lpName在调用CreateMutex时检查是否有相同名称的互斥量已经创建,如果已经创建,则返回已经创建的互斥量的句柄。为确定互斥量是否存在
需要调用GetLastError,如果它返回ERROR_ALREADY_EXISTS,则表示该互斥量已存在,那么即使上面的bInitialOwner设置为TRUE也不能
无法立刻拥有该互斥量
调用WaitForSingleObject将获取互斥量,ReleaseMutex将释放互斥量,注意调用WaitForSingleObject和ReleaseMutex的次数必须相等
线程MyThread1和Mythread2将交替打印i的值
// MyThread.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <commctrl.h>
HANDLE hMutex;
DWORD MyThread1(VOID)
{
INT32 i = 0;
while(1) {
WaitForSingleObject(hMutex, INFINITE);
printf("1:%d/n",i++);
ReleaseMutex(hMutex);
}
return 0;
}
DWORD MyThread2(VOID)
{
INT32 i = 0;
while(1) {
WaitForSingleObject(hMutex, INFINITE);
printf("2:%d/n",i++);
ReleaseMutex(hMutex);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1;
HANDLE hThread2;
hMutex = CreateMutex(NULL,FALSE,NULL);
if(NULL == hMutex) {
printf("Create hMutex error/n");
return -1;
}
hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread1, NULL, 0, NULL);
if(hThread1) {
printf("CreateThread MyThread1 success/r/n");
} else {
printf("CreateThread MyThread1 error/r/n");
return -1;
}
hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread2, NULL, 0, NULL);
if(hThread2) {
printf("CreateThread MyThread2 success/r/n");
} else {
printf("CreateThread MyThread2 error/r/n");
return -1;
}
while(1) {
Sleep(1000);
}
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
- 互斥量
- 互斥量
- 互斥量
- 互斥量
- 互斥量
- 互斥量
- 互斥量
- 互斥量使用方法
- 互斥量理解
- 有关互斥量
- 互斥量Mutex
- 互斥量Mutex
- 6.互斥量
- RAII:互斥量
- Unix互斥量
- 互斥量+信号量
- 信号量&互斥量
- Mutex(互斥量)
- 网站注入与防范的方法
- 网络协议分析软件Sniffer Pro 4.7.5 破解版
- MFC类的层析
- 得到windows系统图标的解决方案(转)
- ixp425上QoS开发
- 互斥量
- cron/tmp.XXXXAqnFoW: No space left on device
- Android 校内头像同步开发笔记
- DirectShow .Net 实现视频
- PB好不好学啊
- SQL查询效率-100w数据查询只要1秒
- XML CDATA的作用
- TBuf和const char*的转换
- 关键词的选择