强制切换一个线程来执行指定的函数
		
    
    
        
        by adie
        
        2013-08-05 12:33:20
        
    
            
        
    	    
  		
		
			
- #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 __declspec(naked) fun2()    
 
- {  
 
-     __asm {   
 
-         pushad   
 
-     }  
 
-   
 
-     printf("fun 2: Hello!\n");    
 
-     printf("fun 2: China!\n");    
 
-   
 
-     InterlockedIncrement(&th2_finished);    
 
-   
 
-     __asm {  
 
-         popad;  
 
-         ret;  
 
-     }  
 
- }    
 
-   
 
- int main()    
 
- {    
 
-     HANDLE hThread = CreateThread(NULL, 0, thread_fun1, 0, 0, 0);    
 
-   
 
-     while(!th1_start)    
 
-         Sleep(1);    
 
-   
 
-     SuspendThread(hThread);    
 
-     CONTEXT ctx;    
 
-     ctx.ContextFlags = CONTEXT_FULL;    
 
-     GetThreadContext(hThread, &ctx);    
 
-   
 
-     ctx.Esp -= 4;  
 
-     *(DWORD*)(DWORD_PTR)ctx.Esp = ctx.Eip;  
 
-     ctx.Eip = (DWORD)(DWORD_PTR)fun2;   
 
-   
 
-     SetThreadContext(hThread, &ctx);    
 
-     FlushInstructionCache(hThread, fun2, 5);  
 
-     ResumeThread(hThread);    
 
-   
 
-     while(!th2_finished)    
 
-     {    
 
-         Sleep(1);    
 
-     }    
 
-   
 
-     InterlockedIncrement(&th1_continue);      
 
-     WaitForSingleObject(hThread, INFINITE);    
 
-     system("pause");    
 
-     return 0;    
 
- }
 
 
上面的代码实现了让本来在执行 thread_fun1 的线程强制切换来执行 fun2 中的代码. 并在 fun2 执行完后返回到原来的位置.
		 
    
		▲评论