Win10下多线程中访问公共变量时,可使用mutex类来做,头文件为mutex,实例(VS2013):
#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>
using namespace std;
mutex mu; //线程互斥对象
int totalNum = 100;
void thread01()
{
while (totalNum > 0)
{
mu.lock(); //同步数据锁
cout << totalNum << endl;
totalNum--;
Sleep(100);
mu.unlock(); //解除锁定
}
}
void thread02()
{
while (totalNum > 0)
{
mu.lock();
cout << totalNum << endl;
totalNum--;
Sleep(100);
mu.unlock();
}
}
int main()
{
thread task01(thread01);
thread task02(thread02);
task01.detach();
task02.detach();
system("pause");
}
输出:
若不加互斥,如下屏蔽:
#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>
using namespace std;
mutex mu; //线程互斥对象
int totalNum = 100;
void thread01()
{
while (totalNum > 0)
{
// mu.lock(); //同步数据锁
cout << totalNum << endl;
totalNum--;
Sleep(100);
// mu.unlock(); //解除锁定
}
}
void thread02()
{
while (totalNum > 0)
{
// mu.lock();
cout << totalNum << endl;
totalNum--;
Sleep(100);
// mu.unlock();
}
}
int main()
{
thread task01(thread01);
thread task02(thread02);
task01.detach();
task02.detach();
system("pause");
}
可看到,有丢失,有重复的现象出现:
参考网址
还可使用如下方法,用WaitForSingleObject和ReleaseMutex:
#include <iostream>
#include <windows.h>
using namespace std;
DWORD bRet;
HANDLE hMutex = NULL;
DWORD WINAPI Fun(LPVOID lpParamter)
{
for (int i = 0; i < 10; i++)
{
bRet = WaitForSingleObject(hMutex, INFINITE);
if (bRet == WAIT_OBJECT_0)
{
// printf("Process is signaled...:%d\n", GetLastError());
}
else if (bRet == WAIT_TIMEOUT)
{
// printf("Time out...:%d\n", GetLastError());
}
else if (bRet == WAIT_FAILED)
{
// printf("Invalid process handle...:%d\n", GetLastError());
}
cout << "A Thread Display!" << endl;
ReleaseMutex(hMutex);
Sleep(100);
}
return 0L;
}
int main()
{
hMutex = CreateMutex(NULL, FALSE, NULL);
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
CloseHandle(hThread);
for (int i = 0; i < 10; i++)
{
WaitForSingleObject(hMutex, INFINITE);
cout << "Main Thread Display!" << endl;
ReleaseMutex(hMutex);
Sleep(200);
}
system("PAUSE");
return 0;
}
结果: