關於windows的進程處理(三)

在多線程下面,有時候會但願等待某一線程完成了再繼續作其餘事情,要實現這個目的,可使用Windows API函數WaitForSingleObject,或者WaitForMultipleObjects。這兩個函數都會等待Object被標爲有信號(signaled)時才返回的。
那麼,什麼是信號呢?簡單來講,Windows下建立的Object都會被賦予一個狀態量。若是Object被激活了,或者正在使用,那麼該Object就是無信號,也就是不可用;另外一方面,若是Object可用了,那麼它就恢復有信號了。這兩個函數的優勢是它們在等待的過程當中會進入一個很是高效沉睡狀態,只佔用極少的CPU時間片。多線程

DWORD WINAPI WaitForSingleObject(
  _In_ HANDLE hHandle,
  _In_ DWORD  dwMilliseconds
);
DWORD WINAPI WaitForMultipleObjects(
  _In_       DWORD  nCount,
  _In_ const HANDLE *lpHandles,
  _In_       BOOL   bWaitAll,
  _In_       DWORD  dwMilliseconds
);

若是該內核對象處於已通知狀態,則該函數當即返回WAIT_OBJECT_0。
若是等待超時,該函數返回WAIT_TIMEOUT。
若是該函數失敗,返回WAIT_FAILED。函數

咱們能夠根據返回值來判斷進程的當前狀態,來決定main函數是否退出。線程

#include "stdafx.h"
#include <Windows.h>
#include <process.h>

unsigned WINAPI ThreadFun1(void *arg)
{
	int cnt = *(int*)arg;
	for (int i = 0; i < cnt; i++)
	{
		Sleep(1000);
		printf("The thread is running.\n");
	}
	return 0;
}

int main()
{
	unsigned threadid;
	int param = 5;
	HANDLE h = (HANDLE)_beginthreadex(NULL, 0, ThreadFun1, &param, 0, &threadid);
	if (h == 0)
	{
		printf("Can not create a thread.\n");
		return 0;
	}
	DWORD st = WaitForSingleObject(h, INFINITE);
	if (st == WAIT_FAILED)
		printf("Failed to wait a thread.\n");
	if (st == WAIT_OBJECT_0)
		printf("The thread is stoped.\n");
	if (st == WAIT_TIMEOUT)
		printf("Timeout to wait a thread.\n");

	printf("End of main.\n");
	return 0;
}

其運行結果以下:code

The thread is running.
The thread is running.
The thread is running.
The thread is running.
The thread is running.
The thread is stoped.
End of main.

這代表main程序等待進程結束後才退出的。對象

但咱們若是將wait函數中的超時設置減小,例如將INFINITE調整爲5000後,則結果以下:進程

DWORD st = WaitForSingleObject(h, 5000);
The thread is running.
The thread is running.
The thread is running.
The thread is running.
Timeout to wait a thread.
End of main.

這就會形成等待進程超時退出一樣也會形成進程的結束。也就是說在短期內運行的進程能夠經過WaitForSingleObject或WaitForMultipleObjects函數來處理,但若是是長時間的進程則有問題了。ip

簡單處理辦法是使用循環等待方法,代碼修改以下:it

DWORD st;
	do {
		printf("Wait a time ...\n");
		st = WaitForSingleObject(h, 3000);
	} while (st == WAIT_TIMEOUT);

其運行結果爲:class

Wait a time ...
The thread is running.
The thread is running.
The thread is running.
Wait a time ...
The thread is running.
The thread is running.
End of main.

從結果上看,這種循環等待是有效果的。thread

相關文章
相關標籤/搜索