Windows10 VS2017 C++多線程傳參和等待線程結束

版權聲明:本文可能爲博主原創文章,若標明出處可隨便轉載。 https://blog.csdn.net/Jailman/article/details/85322164

#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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章