You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.3KB

  1. /***************************************************/
  2. /*! \class Thread
  3. \brief STK thread class.
  4. This class provides a uniform interface for cross-platform
  5. threads. On unix systems, the pthread library is used. Under
  6. Windows, the C runtime threadex functions are used.
  7. Each instance of the Thread class can be used to control a single
  8. thread process. Routines are provided to signal cancelation
  9. and/or joining with a thread, though it is not possible for this
  10. class to know the running status of a thread once it is started.
  11. For cross-platform compatability, thread functions should be
  12. declared as follows:
  13. THREAD_RETURN THREAD_TYPE thread_function(void *ptr)
  14. by Perry R. Cook and Gary P. Scavone, 1995--2017.
  15. */
  16. /***************************************************/
  17. #include "Thread.h"
  18. namespace stk {
  19. Thread :: Thread()
  20. {
  21. thread_ = 0;
  22. }
  23. Thread :: ~Thread()
  24. {
  25. }
  26. bool Thread :: start( THREAD_FUNCTION routine, void * ptr )
  27. {
  28. if ( thread_ ) {
  29. oStream_ << "Thread:: a thread is already running!";
  30. handleError( StkError::WARNING );
  31. return false;
  32. }
  33. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  34. if ( pthread_create(&thread_, NULL, *routine, ptr) == 0 )
  35. return true;
  36. #elif defined(__OS_WINDOWS__)
  37. unsigned thread_id;
  38. thread_ = _beginthreadex(NULL, 0, routine, ptr, 0, &thread_id);
  39. if ( thread_ ) return true;
  40. #endif
  41. return false;
  42. }
  43. bool Thread :: cancel()
  44. {
  45. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  46. if ( pthread_cancel(thread_) == 0 ) {
  47. return true;
  48. }
  49. #elif defined(__OS_WINDOWS__)
  50. TerminateThread((HANDLE)thread_, 0);
  51. return true;
  52. #endif
  53. return false;
  54. }
  55. bool Thread :: wait()
  56. {
  57. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  58. if ( pthread_join(thread_, NULL) == 0 ) {
  59. thread_ = 0;
  60. return true;
  61. }
  62. #elif defined(__OS_WINDOWS__)
  63. long retval = WaitForSingleObject( (HANDLE)thread_, INFINITE );
  64. if ( retval == WAIT_OBJECT_0 ) {
  65. CloseHandle( (HANDLE)thread_ );
  66. thread_ = 0;
  67. return true;
  68. }
  69. #endif
  70. return false;
  71. }
  72. void Thread :: testCancel(void)
  73. {
  74. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  75. pthread_testcancel();
  76. #endif
  77. }
  78. } // stk namespace