thread API:实现线程类

来源:互联网 发布:全途进销存打单软件 编辑:程序博客网 时间:2024/06/06 06:42
  1. //定义WIN32和Linux下通用名称  
  2. typedef void wthread;  
  3.   
  4. //强制退出线程  
  5. int kill_thread(wthread *pthread)  
  6. {  
  7. #ifdef WIN32  
  8.     return(TerminateThread(pthread, 1));  
  9. #else  
  10.     return(pthread_cancel(*(pthread_t *)pthread));  
  11. #endif  
  12. }  
  13.   
  14. //ExitThread是推荐使用的结束一个线程的方法,当调用该函数时,当前线程的栈被释放,然后线程终止  
  15. void exit_thread(void)  
  16. {  
  17. #ifdef WIN32  
  18.     ExitThread(0);  
  19. #else  
  20.     pthread_exit(0);  
  21. #endif  
  22. }  
  23.   
  24. //安全关闭THREAD,推荐使用  
  25. //如果还有其他的进程在使用这个内核对象,那么它就不会被释放  
  26. void free_thread(wthread *pthread)  
  27. {  
  28. #ifdef WIN32  
  29.     CloseHandle(pthread);  
  30. #else  
  31.     delete (pthread_t *)pthread;  
  32. #endif  
  33. }  
  34.   
  35. //等待THREAD  
  36. void wait_thread(wthread *pthread)  
  37. {  
  38. #ifdef WIN32  
  39.     WaitForSingleObject(pthread, INFINITE);  
  40. #else  
  41.     pthread_join(*(pthread_t *)pthread, NULL);  
  42. #endif  
  43. }  
  44.   
  45. //创建线程  
  46. wthread *create_thread(void *(thread_fn)(void *), void *thread_arg)  
  47. {  
  48.     int rv;  
  49. #ifdef WIN32  
  50.     int id;  
  51.     rv =_beginthreadex( NULL, 0, (unsigned int (__stdcall *)(void *))thread_fn, thread_arg, 0, (unsigned int *)&id);  
  52.     return((wthread *)rv);  
  53. #else  
  54.     pthread_t *hThread;  
  55.     hThread = new pthread_t;  
  56.     if(hThread == NULL) {  
  57.         return((wthread *)NULL);  
  58.     }  
  59.     rv = pthread_create(hThread, NULL, (void *(*)(void *))thread_fn, thread_arg);  
  60.     if(rv != 0) {  
  61.         /* thread creation failure */  
  62.         return((wthread *)NULL);  
  63.     }  
  64.     return((wthread *)hThread);  
  65. #endif  
  66. }  
  67.   
  68. //获得当前THREAD 的ID  
  69. long get_threadid(void)  
  70. {  
  71. #ifdef WIN32   
  72.     return GetCurrentThreadId();  
  73. #else   
  74. #ifdef LINUX  
  75.     unsigned long thr_id = pthread_self();  
  76.     thr_id = thr_id << 1;  
  77.     thr_id = thr_id >> 1;  
  78.     return thr_id;  
  79. #else  
  80.     return pthread_self();  
  81. #endif  
  82. #endif  
  83. }
0 0
原创粉丝点击