std::thread线程超时终止

利用std::thread获取线程句柄,再利用GetThreadId获取线程id,利用OpenThread获取句柄。最后调用TerminateThread终止线程。

#include <Windows.h>
#include <thread>
#include <chrono>

struct ThreadParam
{
	bool bExit;
};

void ThreadProcess(void *pParam, int *pRunSataus)
{
	ThreadParam *pThreadParam = (ThreadParam*)pParam;

	while (true)
	{
		int n = 0;
		for (n = 0; n < 30; n++)
		{
			if (pThreadParam->bExit)
			{
				break;
			}
			printf("thread processing...\n");
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
		if (pThreadParam->bExit)
		{
			*pRunSataus = 2;//主动退出
			break;
		}

		*pRunSataus = 1;//正常退出
		break;
	}

	printf("thread exit...\n");
}

int main()
{
	int nRunStatus = 0;
	ThreadParam tpThreadParam;
	tpThreadParam.bExit = false;
	//开启线程
	std::thread t(ThreadProcess, (void *)&tpThreadParam, &nRunStatus);

	//等待线程结束
	bool bStopThreadSuccess = false;
	int nMaxTimeoutSeconds = 10;
	time_t tCurrent, tStart;
	HANDLE hThreadHanle = NULL;
	DWORD dwThreadId = 0;
	time(&tStart);
	if (t.joinable())
	{
	    hThreadHanle = t.native_handle();
		dwThreadId = GetThreadId(hThreadHanle);

		while (true)
		{
			time(&tCurrent);

			if (nRunStatus == 1)
			{
				//正常退出
				t.join();
				bStopThreadSuccess = true;
				break;
			}

			if (difftime(tCurrent, tStart) > nMaxTimeoutSeconds)
			{
				//超时
				nRunStatus = 3;	//超时退出
				HANDLE hThreadHanleBySystem = OpenThread(THREAD_TERMINATE, FALSE, dwThreadId);
				if (hThreadHanleBySystem != NULL)
				{
					t.detach();
					if (::TerminateThread(hThreadHanleBySystem, 0))
					{
						printf("main thread TerminateThread threadid:%u\n", dwThreadId);
						bStopThreadSuccess = true;
					}
					CloseHandle(hThreadHanleBySystem);
				}
				if (bStopThreadSuccess)
				{
					break;
				}
			}
			else
			{
				std::this_thread::sleep_for(std::chrono::seconds(1));
			}
			printf("main thread processing...\n");
		}
	}

	printf("threadid:%u stop:%d runStatus:%d\n", dwThreadId, bStopThreadSuccess == true ? 1 : 0, nRunStatus);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/byxdaz/article/details/129588305