天天看點

c++多線程之_beginthreadex

 線程的原理

c++多線程之_beginthreadex

建立線程

特别注意:如果在代碼中有使用标準C運作庫中的函數時,盡量使用_beginthreadex()來代替CreateThread()

因為_beginthreadex在内部調用了CreateThread,在調用之前_beginthreadex做了很多的工作,進而使得它比CreateThread更安全。

例子一

#include <windows.h>
#include <stdio.h>
#include <process.h>

unsigned Counter;
unsigned __stdcall SecondThreadFunc(void* pArguments)
{
	printf("In second thread...\n");

	while (Counter < 1000000)
		Counter++;

	_endthreadex(0);
	return 0;
}

//建立單個線程執行個體,并等待該線程執行完成
int main()
{
	HANDLE hThread;
	unsigned threadID;

	printf("Creating second thread...\n");

	// Create the second thread.
	hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &threadID);

	// Wait until second thread terminates.
	WaitForSingleObject(hThread, INFINITE);

	printf("Counter should be 1000000; it is-> %d\n", Counter);
	// Destroy the thread object.
	CloseHandle(hThread);
}
           

例子二

}

//建立多子個線程執行個體
#include <stdio.h>
#include <process.h>
#include <windows.h>
//子線程函數
unsigned int __stdcall ThreadFun(PVOID pM)
{
	printf("線程ID号為%4d的子線程說:Hello World\n", GetCurrentThreadId());
	return 0;
}
//主函數,所謂主函數其實就是主線程執行的函數。
int main()
{
	printf("     建立多個子線程執行個體 \n");
	printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");

	const int THREAD_NUM = 5;
	HANDLE handle[THREAD_NUM];
	for (int i = 0; i < THREAD_NUM; i++)
		handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, NULL, 0, NULL);
	WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
	return 0;
}
           
c++多線程之_beginthreadex

WaitForSingleObject()

DWORD WaitForSingleObject( HANDLE hHandle, DWORDdwMilliseconds);

有兩個參數,分别是THandle和Timeout(毫秒機關)。如果想要等待一條線程,那麼你需要指定線程的Handle,以及相應的Timeout時間。當然,如果你想無限等待下去,Timeout參數可以指定系統常量INFINITE。

如果第二個參數為0,那麼函數就測試同步對象的狀态并立即傳回。如果等待逾時,該函數傳回WAIT_TIMEOUT。如果該函數失敗,傳回WAIT_FAILED。可以通過下面的代碼來判斷:

DWORD dw = WaitForSingleObject(hProcess, 5000); //等待一個程序結束,時間為5000ms

switch (dw)

{

case WAIT_OBJECT_0:

// hProcess所代表的程序在5秒内結束

break;

case WAIT_TIMEOUT:

// 等待時間超過5秒

break;

case WAIT_FAILED:

// 函數調用失敗,比如傳遞了一個無效的句柄

break;

}

參考:

https://blog.csdn.net/morewindows/article/details/7421759

c++

繼續閱讀