简单的多线程创建,执行,挂起,终止的例子

简单的多线程创建,执行,挂起,终止的例子.

创建:CreateThread:参数有:线程属性指针,栈大小,线程入口地址,线程参数列表地址,创建标志(0表示立即执行,CREATE_SUSPENDED),线程ID的指针)。

挂起:SuspendThread(HANDLE hThread);

唤醒:ResumeThread(HANDLE hThread);

终止:线程内终止ExitThread(DWORD  dwExitCode);线程外终止:TerminateThread(HANDLE hThread, DWORAD ExitCode);

等待:WaitForSingleObject(HANDLE object, time); 和 WaitForMultipleObject(数量,首指针,是不是全等,最大时间);

创建两个线程,创建时即进入阻塞状态,然后根据主线程的input值,去唤醒或阻塞线程执行。

//简单的多线程创建,执行,挂起,终止的例子
//利用win32 API

#include 
#include 

using namespace std;

DWORD WINAPI FunOne(LPVOID param){
	while (true){
		Sleep(1000);
		cout <<*((int*)param)<< " hello" << endl;
	}
}

DWORD WINAPI FunTwo(LPVOID param){
	while (true){
		Sleep(1000);
		cout << "world" << endl;
	}
}


int main(){
	int input = 0;
	HANDLE hand1 = CreateThread(NULL, 0, FunOne, (void *)&input, CREATE_SUSPENDED, NULL);
	HANDLE hand2 = CreateThread(NULL, 0, FunTwo, (void *)&input, CREATE_SUSPENDED, NULL);
	while (input != 3){
		cin >> input;
		if (input == 1){
			ResumeThread(hand1);
			ResumeThread(hand2);
		}
		else if (input == 2){
			SuspendThread(hand1);
			SuspendThread(hand2);
		}
	}
	TerminateThread(hand1, 1);
	TerminateThread(hand2, 2);
	return 0;
}


你可能感兴趣的:(windows多线程)