thread API:实现线程类

本文详细介绍了在Windows和Linux环境下实现通用线程操作的方法,包括强制退出线程、安全关闭线程、等待线程结束以及线程创建等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值