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.
DWORD WINAPI ThreadFunc1(PVOID pvParam)
_tprintf_s(_T("I am ThreadFunc1\n"));
DWORD WINAPI ThreadFunc2(PVOID pvParam)
_tprintf_s(_T("I am ThreadFunc2\n"));
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);
// lets give the thread some time to do some work
// get control registers such as EIP (instruction pointer)
cThread.ContextFlags = CONTEXT_CONTROL;
// change the target thread path of execution to ThreadFunc2
cThread.Eip = (DWORD)ThreadFunc2;