Windows10 VS2017 C++多线程传参和等待线程结束


#include "pch.h"
#include 
#include 

using namespace std;

typedef struct MyData
{
	const char* str;
}MYDATA;

//线程函数
DWORD WINAPI Fun(LPVOID lpParamter)
{
	MYDATA *pmd = (MYDATA *)lpParamter;
	for (int i = 0; i < 10; i++)
	{
		cout << "Displaying " << pmd->str << endl;
		Sleep(500);
	}
	return 0;

}

int main()
{
	//使用struct传递参数
	MYDATA xstr;
	xstr.str = "你好!";

	//使用GetExitCodeThread()轮询检查
	//DWORD exitCode = 0;
	//HANDLE hThread = CreateThread(NULL, 0, Fun, &xstr, 0, NULL);
	//while (1) {
	//	GetExitCodeThread(hThread, &exitCode); // 严重浪费 CPU 时间
	//	if (STILL_ACTIVE != exitCode)
	//		break;
	//}
	//CloseHandle(hThread);

	//WaitForSingleObject(),cpu使用率极低
	HANDLE hThread = CreateThread(NULL, 0, Fun, &xstr, 0, NULL);
	WaitForSingleObject(hThread, INFINITE); // 等待,直到线程被激发
	CloseHandle(hThread);

	cout << "Child thread is over." << endl;
	return 0;

}

参考文章:
https://www.cnblogs.com/XiHua/p/5028329.html

你可能感兴趣的:(编程人生)