1. 程式人生 > >Windows10 VS2017 C++多執行緒傳參和等待執行緒結束

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


#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