[C/C++][boost] boost::thread - boost::mutex


나중에 boost thread 정리를 좀 제대로 해서 포스팅 해야겠다 -_-;

일단 급한대로..


  1. #include <boost/thread/thread.hpp>  
  2. #include <boost/thread/mutex.hpp>  
  3. #include <boost/thread/condition.hpp>  
  4. #include <boost/date_time/posix_time/posix_time.hpp>  
  5. #include <boost/bind.hpp>   
  6.   
  7. class BoostThreadEx  
  8. {  
  9. public:  
  10.     BoostThreadEx(void)  
  11.     : m_pThread1(NULL)  
  12.     , m_pThread2(NULL)  
  13.     , m_bThreadContinue(false)  
  14.     , m_nThreadCount(0) {}  
  15.     virtual BoostThreadEx(void);  
  16.        
  17.     void startThread();  
  18.     void threadFunc(const char* pc, int i);  
  19. private:  
  20.     boost::thread* m_pThread1;  
  21.     boost::thread* m_pThread2;  
  22.     boost::mutex m_Mutex;  
  23. //  boost::condition m_Condition;  
  24.     bool m_bThreadContinue;  
  25.     int m_nThreadCount;  
  26. };  
  27.   
  28. BoostThreadEx::BoostThreadEx(void)  
  29. {  
  30.     if(m_pThread1)  
  31.     {  
  32.         m_pThread1->join();  
  33.         delete m_pThread1;  
  34.         m_pThread1 = NULL;  
  35.     }  
  36.     if(m_pThread2)  
  37.     {  
  38.         m_pThread2->join();  
  39.         delete m_pThread2;  
  40.         m_pThread2 = NULL;  
  41.     }  
  42. }  
  43.   
  44. void BoostThreadEx::startThread();  
  45. {  
  46.     if(!m_pThread1 && !m_pThread2)  
  47.     {  
  48.         m_pThread1 = new boost::thread(boost::bind(&BoostThreadEx::threadFunc, this"Thread Test", 1));  
  49.         m_pThread2 = new boost::thread(boost::bind(&BoostThreadEx::threadFunc, this"Thread Test", 2));  
  50.         m_bThreadContinue = true;  
  51.     }  
  52. }  
  53.   
  54. void BoostThreadEx::threadFunc(const char* pc, int i)  
  55. {  
  56.     while(m_bThreadContinue)  
  57.     {  
  58.         if(m_bThreadContinue) break;  
  59. //      boost::posix_time::millisec const waiting_duration(500);  
  60. //      {  
  61. //          boost::mutex::scoped_lock lock(m_Mutex);  
  62. //          m_Condition.timed_wait(lock, waiting_duration);  
  63. //      }  
  64.   
  65.         {  
  66.             boost::scoped_lock mlock(m_Mutex);  
  67.             printf("%s%d\n", pc, i);  
  68.         }  
  69.           
  70.         if(m_nCount++ >= 100) m_bThreadContinue = false;  
  71.     }  
  72. }  

text 편집기로 대강 짰는데 컴파일 되려나 ㅋㅋㅋ