Windows10 VS2017 C++多執行緒傳參和等待執行緒結束

大囚長發表於2018-12-28

#include "pch.h"
#include <iostream>
#include <windows.h>

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

相關文章