WindowsAPI里的多线程简单例子,先记下来,以后再学学
#include <windows.h>
#include <iostream>
using namespace std;
//线程处理函数
DWORD WINAPI Fun1(LPVOID lpParam);
DWORD WINAPI Fun2(LPVOID lpParam);
int tickets = 20;
void main()
{
HANDLE hThread1, hThread2;
hThread1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cin.get();
}
DWORD WINAPI Fun1(LPVOID lpParam)
{
while(true)
{
if(tickets > 0)
cout<<"Thread1 sell ticket : "<<tickets--<<endl;
else break;
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParam)
{
while(true)
{
if(tickets > 0)
cout<<"Thread2 sell ticket : "<<tickets--<<endl;
else break;
}
return 0;
}
这里在main里用两个函数Fun1和Fun2建了两个线程,有一个全局变量ticket=20表示20张票,分由两个线程进行出售。
但是这个程序运行起来结果会出现混乱和不确定:
原因很简单,在操作系统里都学过关于同步的问题,这里的两个线程之间就没有对临界资源ticket进行同步。类似于操作系统里的PV操作,可以将程序改为:
#include <windows.h>
#include <iostream>
using namespace std;
//线程处理函数
DWORD WINAPI Fun1(LPVOID lpParam);
DWORD WINAPI Fun2(LPVOID lpParam);
int tickets = 20;
HANDLE hMutex;
void main()
{
hMutex = CreateMutex(NULL, false, NULL);
HANDLE hThread1, hThread2;
hThread1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cin.get();
}
DWORD WINAPI Fun1(LPVOID lpParam)
{
while(true)
{
WaitForSingleObject(hMutex, INFINITE);
if(tickets > 0)
cout<<"Thread1 sell ticket : "<<tickets--<<endl;
else break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParam)
{
while(true)
{
WaitForSingleObject(hMutex, INFINITE);
if(tickets > 0)
cout<<"Thread2 sell ticket : "<<tickets--<<endl;
else break;
ReleaseMutex(hMutex);
}
return 0;
}
这里用了一个信息量Mutex来对ticket进行同步操作,进程要操作ticket之前必须先获得信号量,使用完之后释放以使整个过程能继续下去。
最后得到正常的结果为: