Event.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* -*- C++ -*- */
  2. /****************************************************************************
  3. ** Copyright (c) 2001-2014
  4. **
  5. ** This file is part of the QuickFIX FIX Engine
  6. **
  7. ** This file may be distributed under the terms of the quickfixengine.org
  8. ** license as defined by quickfixengine.org and appearing in the file
  9. ** LICENSE included in the packaging of this file.
  10. **
  11. ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
  12. ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  13. **
  14. ** See http://www.quickfixengine.org/LICENSE for licensing information.
  15. **
  16. ** Contact ask@quickfixengine.org if any conditions of this licensing are
  17. ** not clear to you.
  18. **
  19. ****************************************************************************/
  20. #ifndef FIX_EVENT_H
  21. #define FIX_EVENT_H
  22. #include "Utility.h"
  23. #include <math.h>
  24. #ifndef _MSC_VER
  25. #include <pthread.h>
  26. #include <cmath>
  27. #endif
  28. namespace FIX
  29. {
  30. /// Portable implementation of an event/conditional mutex
  31. class Event
  32. {
  33. public:
  34. Event()
  35. {
  36. #ifdef _MSC_VER
  37. m_event = CreateEvent( 0, false, false, 0 );
  38. #else
  39. pthread_mutex_init( &m_mutex, 0 );
  40. pthread_cond_init( &m_event, 0 );
  41. #endif
  42. }
  43. ~Event()
  44. {
  45. #ifdef _MSC_VER
  46. CloseHandle( m_event );
  47. #else
  48. pthread_cond_destroy( &m_event );
  49. pthread_mutex_destroy( &m_mutex );
  50. #endif
  51. }
  52. void signal()
  53. {
  54. #ifdef _MSC_VER
  55. SetEvent( m_event );
  56. #else
  57. pthread_mutex_lock( &m_mutex );
  58. pthread_cond_broadcast( &m_event );
  59. pthread_mutex_unlock( &m_mutex );
  60. #endif
  61. }
  62. void wait( double s )
  63. {
  64. #ifdef _MSC_VER
  65. WaitForSingleObject( m_event, (long)(s * 1000) );
  66. #else
  67. pthread_mutex_lock( &m_mutex );
  68. timespec time, remainder;
  69. double intpart;
  70. time.tv_nsec = (long)(modf(s, &intpart) * 1e9);
  71. time.tv_sec = (int)intpart;
  72. pthread_cond_timedwait( &m_event, &m_mutex, &time );
  73. pthread_mutex_unlock( &m_mutex );
  74. #endif
  75. }
  76. private:
  77. #ifdef _MSC_VER
  78. HANDLE m_event;
  79. #else
  80. pthread_cond_t m_event;
  81. pthread_mutex_t m_mutex;
  82. #endif
  83. };
  84. }
  85. #endif