Thread.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Thread.cpp
  3. * Copyright © 2012 kbinani
  4. *
  5. * This file is part of vConnect-STAND.
  6. *
  7. * vConnect-STAND is free software; you can redistribute it and/or
  8. * modify it under the terms of the GPL License.
  9. *
  10. * vConnect-STAND is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. */
  14. #include "Thread.h"
  15. #include <stdlib.h>
  16. namespace vconnect
  17. {
  18. #ifdef _WIN32
  19. Thread::Thread( ThreadWorker start, void *argument )
  20. {
  21. this->thread = (HANDLE)_beginthreadex( NULL, 0, start, argument, 0, NULL );
  22. }
  23. void Thread::join()
  24. {
  25. WaitForSingleObject( this->thread, INFINITE );
  26. }
  27. Thread::~Thread()
  28. {
  29. CloseHandle( this->thread );
  30. }
  31. void Thread::tellThreadEnd()
  32. {
  33. _endthreadex( 0 );
  34. }
  35. void Thread::sleep( unsigned int milliseconds )
  36. {
  37. Sleep( milliseconds );
  38. }
  39. #else
  40. Thread::Thread( ThreadWorker worker, void *argument )
  41. {
  42. this->thread = (pthread_t *)malloc( sizeof( pthread_t ) );
  43. pthread_create( this->thread, NULL, worker, argument );
  44. }
  45. void Thread::join()
  46. {
  47. pthread_join( *this->thread, NULL );
  48. }
  49. Thread::~Thread()
  50. {
  51. free( this->thread );
  52. }
  53. void Thread::tellThreadEnd()
  54. {
  55. }
  56. void Thread::sleep( unsigned int milliseconds )
  57. {
  58. struct timespec spec;
  59. time_t seconds = (time_t)(milliseconds / 1000.0);
  60. long nanoSeconds = (long)((milliseconds - seconds * 1000) * 1000);
  61. spec.tv_sec = seconds;
  62. spec.tv_nsec = nanoSeconds;
  63. nanosleep( &spec, NULL );
  64. }
  65. #endif
  66. }