- #include <stdio.h>
- #define _WIN32_WINNT 0x0501
- #include <windows.h>
-
- volatile long th1_start = 0;
- volatile long th1_continue = 0;
- volatile long th2_finished = 0;
-
- DWORD WINAPI thread_fun1(LPVOID arg)
- {
-
- InterlockedIncrement(&th1_start);
-
- while(!th1_continue)
- {
- Sleep(1);
- }
-
- printf("fun 1: Hello!\n");
- printf("fun 1: World!\n");
-
- return 0;
- }
-
- void fun2()
- {
- printf("fun 2: Hello!\n");
- printf("fun 2: China!\n");
-
- InterlockedIncrement(&th2_finished);
-
- while(1)
- {
- Sleep(50);
- }
- }
-
- long WINAPI ExceptionFilter(struct _EXCEPTION_POINTERS* ep)
- {
- printf("Exception...\n");
- return EXCEPTION_EXECUTE_HANDLER;
- }
-
- int main()
- {
-
-
-
-
- HANDLE hThread = CreateThread(NULL, 0, thread_fun1, 0, 0, 0);
-
- while(!th1_start)
- Sleep(1);
-
- BYTE* tempStack = new BYTE[1024 * 1024];
-
-
- SuspendThread(hThread);
- CONTEXT ctx;
- ctx.ContextFlags = CONTEXT_FULL;
- GetThreadContext(hThread, &ctx);
-
- DWORD saveOldESP = ctx.Esp;
- DWORD saveOldEIP = ctx.Eip;
-
- ctx.Esp = (DWORD)(DWORD_PTR)tempStack + 1024 * 1024;
- ctx.Eip = (DWORD)(DWORD_PTR)fun2;
- SetThreadContext(hThread, &ctx);
- ResumeThread(hThread);
-
- while(!th2_finished)
- {
- Sleep(1);
- }
-
- InterlockedIncrement(&th1_continue);
-
- SuspendThread(hThread);
- ctx.Esp = saveOldESP;
- ctx.Eip = saveOldEIP;
- SetThreadContext(hThread, &ctx);
- ResumeThread(hThread);
-
- delete [] tempStack;
- WaitForSingleObject(hThread, INFINITE);
- system("pause");
- return 0;
- }
上面这份代码想强制把一个指定线程切换来调用一个指定函数, 调用完了后让线程继续回到原来的地方运行.
在 VC2005 下, Release 版可以正常工作, 输出
fun 2: Hello!
fun 2: China!
fun 1: Hello!
fun 1: World!
Debug 版按 F5 运行也正常, 但是 Ctrl + F5 的话就直接退掉了, 捕获不到发生了什么异常. 如果把 mark1, makr2 任意一个注释打开, Debug 版 Ctrl + F5 运行就正常了.
这到底是什么原因造成的啊? 是切换线程上下文的时候线程在内核态运行造成的么....