3线程

来源:互联网 发布:商务背包 知乎 编辑:程序博客网 时间:2024/05/16 05:39
#include <windows.h>
#include <iostream>
using namespace std;
static  int count1 = 1;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data
DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data
DWORD WINAPI Fun3Proc(LPVOID lpParameter);//thread data




HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
HANDLE hThread3;
//创建线程


hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
hThread3 = CreateThread(NULL, 0, Fun3Proc, NULL, 0, NULL);


CloseHandle(hThread1);
CloseHandle(hThread2);
CloseHandle(hThread3);


//创建互斥对象
hMutex = CreateMutex(NULL, TRUE, (LPCWSTR)"count1");
if (hMutex)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
return;
}
}
WaitForSingleObject(hMutex, INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);


Sleep(4000);
}
//线程1的入口函数
DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data
{
while (true)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex, INFINITE);
if (count1<100)
{
Sleep(1000);
count1+=2;
}
/*else
break;*/
ReleaseMutex(hMutex);
}


return 0;
}
//线程2的入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data
{
while (true)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex, INFINITE);
if (count1<100)
{
Sleep(2000);
count1 -= 1;
}
/*else
break;*/
ReleaseMutex(hMutex);
}


return 0;
}


//线程3的入口函数
DWORD WINAPI Fun3Proc(LPVOID lpParameter)//thread data
{
while (true)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex, INFINITE);
if (count1==100)
{
exit(0);
}
else if (count1 % 5 == 0)
{
cout << count1<<endl;
}
//break;
ReleaseMutex(hMutex);
}


return 0;
}
0 0
原创粉丝点击