Thread.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "Thread.h"
  2. Thread::Thread(): m_isstop(true), m_autoDelete(false)
  3. {
  4. }
  5. Thread::~Thread()
  6. {
  7. if(!m_isstop)
  8. {
  9. SDL_KillThread(m_t);
  10. m_t = 0;
  11. }
  12. for(std::map<std::string, SDL_mutex*>::iterator mutex = m_mutexs.begin();mutex != m_mutexs.end();mutex++)
  13. SDL_DestroyMutex(mutex->second);
  14. }
  15. bool Thread::start()
  16. {
  17. if(m_isstop)
  18. {
  19. m_t = SDL_CreateThread(Thread::ThreadInit, this);
  20. if(m_t != 0)
  21. {
  22. m_isstop = false;
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. void Thread::stop()
  29. {
  30. if(!m_isstop)
  31. {
  32. SDL_KillThread(m_t);
  33. m_t = 0;
  34. }
  35. m_isstop = true;
  36. }
  37. void Thread::join()
  38. {
  39. SDL_WaitThread(m_t, 0);
  40. m_isstop = true;
  41. }
  42. void Thread::setAutoDelete(bool autoDelete)
  43. {
  44. m_autoDelete = autoDelete;
  45. }
  46. int Thread::ThreadInit(void* param)
  47. {
  48. Thread *t(reinterpret_cast<Thread*>(param));
  49. t->run();
  50. if(t->m_autoDelete)
  51. delete t;
  52. return 0;
  53. }
  54. bool Thread::threadRunning()
  55. {
  56. return m_isstop;
  57. }
  58. bool Thread::createLockMutex(std::string name)
  59. {
  60. std::map<std::string, SDL_mutex*>::iterator mutex = m_mutexs.find(name);
  61. if(m_mutexs.find(name) == m_mutexs.end())
  62. {
  63. m_mutexs[name] = SDL_CreateMutex();
  64. mutex = m_mutexs.find(name);
  65. }
  66. if(SDL_mutexP(mutex->second)==-1)
  67. return false;
  68. return true;
  69. }
  70. bool Thread::lockMutex(std::string name)
  71. {
  72. std::map<std::string, SDL_mutex*>::iterator mutex = m_mutexs.find(name);
  73. if(m_mutexs.find(name) == m_mutexs.end())
  74. return false;
  75. if(SDL_mutexP(mutex->second)==-1)
  76. return false;
  77. return true;
  78. }
  79. bool Thread::unlockMutex(std::string name)
  80. {
  81. std::map<std::string, SDL_mutex*>::iterator mutex = m_mutexs.find(name);
  82. if(m_mutexs.find(name) == m_mutexs.end())
  83. return false;
  84. if(SDL_mutexV(mutex->second)==-1)
  85. return false;
  86. return true;
  87. }