初次嘗試C++多線程(濃縮版)

// test_thread.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
//
//
//int main()
//{
//    return 0;
//}
#include <iostream>
#include <ctime>
#include <windows.h>
using namespace std;

void sleepdelay(float t)
{
	clock_t delay = t*CLOCKS_PER_SEC;
	clock_t start = clock();
	while ((clock() - start) < delay)
	{
	}
}
DWORD WINAPI thread_one(LPVOID s)
{
	for (int i = 0; i < 10; i++)
	{
		cout << "this is one thread,ID is" << GetCurrentThreadId() << endl;
		sleepdelay(0.6);
	}
	return 0;
}
DWORD WINAPI thread_two(LPVOID s)
{
	for (int i = 0; i < 10; i++)
	{
		cout << "this is two thread,ID is" << GetCurrentThreadId() << endl;
		sleepdelay(0.7);
	}
	return 0;
}
int main()
{
	HANDLE handle_one = CreateThread(NULL, 0, thread_one, NULL, 0, NULL);
	//WaitForSingleObject(handle_one, INFINITE);//掛起當前線程,等待線程handle_one返回信號,第二個參數是等待時間最大值,INFNITE是指無限等待;
	CloseHandle(handle_one);
	HANDLE handle_two = CreateThread(NULL, 0, thread_two, NULL, 0, NULL);
	CloseHandle(handle_two);

	for (int i = 0; i < 10; i++)
	{
		cout << "this is main thread,ID is" << GetCurrentThreadId() << endl;
		sleepdelay(0.5);
	}
	return 0;
}


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