Thread.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Copyright (c) 2006-2013 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "Thread.h"
  21. namespace love
  22. {
  23. namespace thread
  24. {
  25. namespace sdl
  26. {
  27. Thread::Thread(Threadable *t)
  28. : t(t)
  29. , running(false)
  30. , thread(0)
  31. {
  32. }
  33. Thread::~Thread()
  34. {
  35. if (!running) // Clean up handle
  36. wait();
  37. /*
  38. if (running)
  39. wait();
  40. FIXME: Needed for proper thread cleanup
  41. */
  42. }
  43. bool Thread::start()
  44. {
  45. Lock l(mutex);
  46. if (running)
  47. return false;
  48. if (thread) // Clean old handle up
  49. SDL_WaitThread(thread, 0);
  50. thread = SDL_CreateThread(thread_runner, NULL, this);
  51. running = (thread != 0);
  52. return running;
  53. }
  54. void Thread::wait()
  55. {
  56. {
  57. Lock l(mutex);
  58. if (!thread)
  59. return;
  60. }
  61. SDL_WaitThread(thread, 0);
  62. Lock l(mutex);
  63. running = false;
  64. thread = 0;
  65. }
  66. bool Thread::isRunning()
  67. {
  68. Lock l(mutex);
  69. return running;
  70. }
  71. int Thread::thread_runner(void *data)
  72. {
  73. Thread *self = (Thread *) data; // some compilers don't like 'this'
  74. self->t->threadFunction();
  75. Lock l(self->mutex);
  76. self->running = false;
  77. return 0;
  78. }
  79. } // sdl
  80. } // thread
  81. } // love