Changing Thread Path of Execution
Posted by MHesham on August 11, 2011
Every thread has a context structure, which is maintained inside the thread’s kernel object. This context structure reflects the state of the thread’s CPU registers when the thread was last executing.
Every 20 milliseconds or so (as returned by the second parameter of the GetSystemTimeAdjustment function), Windows looks at all the thread kernel objects currently in existence. Of these objects, only some are considered schedulable. Windows selects one of the schedulable thread kernel objects and loads the CPU’s registers with the values that were last saved in the thread’s context. This action is called a context switch.
The code primary thread (main function) below creates a new thread where its entry point is ThreadFunc1, and while it is running it suspends this secondary and changes its path of execution to the address of another function.
Code
DWORD WINAPI ThreadFunc1(PVOID pvParam)
{
_tprintf_s(_T("I am ThreadFunc1\n"));
while(1)
{
}
_tprintf_s(_T("Exiting ThreadFunc1\n"));
return 0;
}
DWORD WINAPI ThreadFunc2(PVOID pvParam)
{
_tprintf_s(_T("I am ThreadFunc2\n"));
while(1)
{
}
_tprintf_s(_T("Exiting ThreadFunc2\n"));
return 0;
}
int _tmain(int argc, TCHAR* argv[])
{
// create a new thread with ThreadFunc1 as its entry-point
HANDLE hThread = chBEGINTHREADEX(NULL, 0, ThreadFunc1, NULL, 0, NULL);
if(!hThread)
PrintLastError();
// lets give the thread some time to do some work
Sleep(2000);
SuspendThread(hThread);
CONTEXT cThread;
// get control registers such as EIP (instruction pointer)
cThread.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(hThread, &cThread);
// change the target thread path of execution to ThreadFunc2
cThread.Eip = (DWORD)ThreadFunc2;
SetThreadContext(hThread, &cThread);
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
Output
This entry was posted on August 11, 2011 at 7:31 PM and is filed under Development, Operating Systems, Windows Programming. Tagged: context, thread context switching, threads, winapi, windows programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.