// 多线程.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while (1) {
//WaitForSingleObject(hMutex, INFINITE);
cout << "Fun display!" << endl;
Sleep(1000);
//ReleaseMutex(hMutex);
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL); //开启一个线程(#,#,线程函数,参数,#,#)
//hMutex = CreateMutex(NULL, FALSE, L"screen");//创建一个独占资源(NULL,该资源不是归属于创建它的进程,资源名称)
CloseHandle(hThread); //关掉线程句柄,回收资源,但创建的线程并不会关掉,线程的生命周期就是线程函数从开始执行到return,线程句柄的生命周期是从CreateThread返回到你CloseHandle()。
while (1) {
WaitForSingleObject(hMutex, INFINITE); //申请资源(资源的句柄,没有申请到就一直等待,也可为数字(等待时间,单位ms))
cout << "main display!" << endl;
Sleep(2000);
//ReleaseMutex(hMutex); //释放该独占资源,此后该资源可以被其他线程申请
}
return 0;
}