C++多线程及线程锁创建
ThreadLock.cpp:
#include<Windows.h>
#include<iostream>
using namespace std;
HANDLE lock;//互斥锁
DWORD WINAPI MyThread2(LPVOID lpParamter)
{
while (1)
{
WaitForSingleObject(lock, INFINITE);
cout << "MyThread2" << endl;
Sleep(1000);
ReleaseMutex(lock);
//Sleep(3000);
}
}
DWORD WINAPI MyThread1(LPVOID lpParamter)
{
while (1)
{
WaitForSingleObject(lock, INFINITE);
cout << "MyThread1"<< endl;
Sleep(1000);
ReleaseMutex(lock);
}
}
int main()
{
lock = CreateMutex(NULL, FALSE, NULL);//创建一个锁
HANDLE hThread1 = CreateThread(NULL, 0, MyThread1, NULL, 0, NULL);
CloseHandle(hThread1);
HANDLE hThread2 = CreateThread(NULL, 0, MyThread2, NULL, 0, NULL);
CloseHandle(hThread2);
while (1)
{
Sleep(10);
};
return 0;
}