C++ Thread

Started by
3 comments, last by MJP 16 years, 2 months ago
Hi, I have a simple multi threaded program in C++ and i would like to find out whether a specific thread is currently running but im unsure as how to do this.

unsigned __stdcall Task::TaskA(void *pArgs) 
{
	// Do something here
	return 1;
}

void Task::Start()
{
	// Create thread.
	hThread = (HANDLE)_beginthreadex( NULL, 0, &Task::TaskA, NULL, 0, &threadID );
	cout << "Thread " << threadID << " started" << endl;
}

void Task::Finish()
{
	// End the thread
	_endthreadex(0);
	// Close the Handle to the thread
	if(this->hThread)	CloseHandle(hThread);
	cout << "Thread " << threadID << " destroyed" << endl;
} 
This is what i have so far. Is there a simple way of finding out for a specific thread if it currently running or not? Other than this i would have a running bool for each task object which i could set true in the start method, false in the finish etc. Which would be the best option? Cheers [Edited by - TigerSam on February 12, 2008 3:06:04 PM]
Advertisement
If you only want to wait for a thread to finish processing before doing something you can make a call to WaitForSingleObject and pass in the thread handle returned by _beginthreadex and a timeout value (INFINITE is defined as 0xFFFFFFFF). This will of course cause the calling thread to stall until the thread ends and your method returns. Beyond this I know of no call to say "is this thread currently running at this time" because if that's the case then the calling thread would not have a time slice and would always return false.
From the CreateThread documentation (_beginthreadex calls CreateThread internally):
"When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object."

Which means you can use WaitForSingleObject to wait on the handle returned from CreateThread() / _beginthreadex() to see if the handle is signalled. If it is, the thread has terminated.

EDIT: Too slow again :(
Cheers Guys that helped me out. Thanks
Never, ever, call TerminateThread (or even SuspendThread) unless you really have to. Very bad things can happen, since it causes the thread to stop dead in it's tracks. It can cause destructors not to be called, locks to be kept locked, and resources to be leaked.

Also you should be careful about calling ExitThread as well, as it can cause the same problems.

This topic is closed to new replies.

Advertisement