//C++ Builder 6.0
//一个简单的多线程演示程序
//【LINK】http://hi.baidu.com/xiandanshiyi/item/3ad6e1e567fc67324cdcaf53
//---------------------------------------------------------------------------
#include <iostream>
#include <windows.h>
using namespace std;
#pragma hdrstop
HANDLE hMutex;
//---------------------------------------------------------------------------
DWORD WINAPI Fun(LPVOID lpParamter)
{
while(1)
{
WaitForSingleObject(hMutex, INFINITE); //申请资源
cout<<"Fun display!"<<endl;
Sleep(1000);
ReleaseMutex(hMutex); //释放一个独占资源
}
}
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE, "screen"); //创建一个独占资源
CloseHandle(hThread);
while(1)
{
// /*
WaitForSingleObject(hMutex, INFINITE); //申请资源
cout<<"main display!"<<endl;
Sleep(2000);
// */
ReleaseMutex(hMutex); //释放一个独占资源
}
return 0;
}
//---------------------------------------------------------------------------
//main函数中,必须有无限循环(即便循环体为空),否则程序将退出——线程中的fun函数没有时间执行
//若不使用独占资源(带注释行),则输出不符合预期 -- 输出混乱;去掉注释,输出情况完全符合预期
小字-多线程技术研究(一)
最新推荐文章于 2024-09-10 21:31:25 发布
