第一篇,第二章 之 ExitThread() (结束一个线程)

强制结束一个线程

 

VOID    ExitThread(

     DWORD   dwExitCode          //in,打定此线程被强制结束后,线程返回的值

);

 

说明:线程中,放在此函数之后的任何代码,不会被执行

 

 

程序启动后就执行的那个线程称 主线程,

主线程,必须负责 GUI 程序中的主消息循环,

          它结束( 正常返回或调用ExitThread() ),整个程序就结束,程序中的所有线程都被强制结束,

                其它线程没有机会 调用 CloseHandle() 与线程核心对象"脱离",即不能使线程核心对象引用计数减1

                对系统来说,这是资源的浪费

 警告: 主线程必须在其它线程都结束之后,才能结束.

 

* * ExitThrd.c * * Sample code for "Multithreading Applications in Win32" * This is from Chapter 2, Listing 2-3 * * Demonstrate ExitThread */ #define WIN32_LEAN_AND_MEAN #include #include #include DWORD WINAPI ThreadFunc(LPVOID); void AnotherFunc(void); int main() { HANDLE hThrd; DWORD exitCode = 0; DWORD threadId; //创建线程 hThrd = CreateThread(NULL, 0, ThreadFunc, (LPVOID)1, 0, &threadId ); if (hThrd) printf("Thread launched1/n"); //循环刺探 线程 是否结束 for(;;) { BOOL rc; rc = GetExitCodeThread(hThrd, &exitCode); if (rc && exitCode != STILL_ACTIVE ) break; } //线程核心对象引用计数减1 CloseHandle(hThrd); printf("Thread returned %d/n", exitCode); return EXIT_SUCCESS; } /* * Call a function to do something that terminates * the thread with ExitThread instead of returning. */ DWORD WINAPI ThreadFunc(LPVOID n) { printf("Thread running/n"); AnotherFunc(); //线程中调用其它函数 return 0; } void AnotherFunc() { printf("About to exit thread/n"); ExitThread(4); //强制退出 此函数所在的线程 // It is impossible to get here, this line // will never be printed printf("This will never print/n"); }   

//以上代码,存储进text文件,以.c为扩展名,拖进VC 6.0,编译,运行.

 

我测试后,有两种结果,为何? 这两种结果是随机出现的

 

第一种

  Thread launched1
  Thread running
  About to exit thread
  Thread returned 4

 

 

第二种

 Thread launched1             //出现两次,为何?????
 Thread launched1
 Thread running
 About to exit thread
 Thread returned 4

你可能感兴趣的:(Win_Thread)