WINDOWS API ——CREATEMUTEX——创建互斥对象(转)
互斥对象是系统内核维护的一种数据结构,它保证了对象对单个线程的访问权 互斥对象的结构:包含了一个使用数量,一个线程ID,一个计数器 使用数量是指有多少个线程在调用该对象,线程ID是指互斥对象维护的线程的ID 计数器表示当前线程调用该对象的次数
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, 安全属性结构指针BOOL bInitialOwner, //是否占有该互斥量 LPCTSTR lpName //设置互斥对象的名字 );
如果一个线程拥有了一个互斥对象后,当该线程运行完成后就要释放该互斥对象,不然其他的线程得不到互斥对象则无法运行
用ReleaseMutex(HWND);
它的具体作用是每调用它一次将互斥对象的计数器减一,直到减到零为止,此时释放互斥对象,并将互斥对象中的线程id 置零。 它的使用条件是,互斥对象在哪个线程中被创建,就在哪个线程里面释放。因为调用的时候会检查当前线程的id是不是
与互斥对象中保存的id一致,若一致,则此次操作有效,不一致,则无效。
#include <iostream>#include <afx.h>#include <process.h>using namespace std;HANDLE hUp;CRITICAL_SECTION g_data;int arr[10];HANDLE hMutex; //使用手动重置为无信号状态,初始化时有信号状态UINT __stdcall Add(LPVOID lParam){DWORD dReturn = WaitForSingleObject(hMutex,INFINITE);for (int i = 0; i<10;i++ ){arr[i]=i;//0-9}for (int i = 0;i < 10; i++){cout<<arr[i]<<" ";}cout<<endl;ReleaseMutex(hMutex);return 1;
}UINT __stdcall Add2(LPVOID lParam)
{DWORD dReturn = WaitForSingleObject(hMutex,INFINITE);for (int i = 0; i<100 ;i++){arr [i] = i+100;//10`1}for (int i = 0;i < 10; i++){cout<<arr[i]<<" ";}cout<<endl;ReleaseMutex(hMutex);return 1;
}int main()
{hMutex = CreateMutex(NULL,FALSE,"");hUp=(HANDLE)_beginthreadex(NULL, 0, Add, NULL, NULL, 0);hUp=(HANDLE)_beginthreadex(NULL, 0, Add2, NULL, NULL, 0);Sleep(5000);
}
在Qt creator上面运行,需要在pro文件中添加
CONFIG +=c++11
DEFINES-= UNICODE
缺少第一个会否则会出现This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.缺少第二个会出现
cannot convert 'const char*' to 'LPCWSTR {aka const wchar_t*}' for argument '3' to 'void* CreateMutexW(LPSECURITY_ATTRIBUTES, WINBOOL, LPCWSTR)'
hMutex = CreateMutex(NULL,FALSE,"");