1 //============================================================================ 2 // Name : thread.cpp 3 // Author : LittleKu 4 // Version : 5 // Copyright : LittleKu 6 // Description : thread in C++, Ansi-style 7 //============================================================================ 8 9 #include <pthread.h> 10 #include <unistd.h> 11 #include <stdio.h> 12 13 using namespace std; 14 15 class Thread { 16 public: 17 Thread() { 18 this->_flag = 0; 19 this->_threadID = 0; 20 ::pthread_mutex_init(&this->_mutex, NULL); 21 ::pthread_cond_init(&this->_cond, NULL); 22 } 23 virtual ~Thread() { 24 ::pthread_mutex_destroy(&this->_mutex); 25 ::pthread_cond_destroy(&this->_cond); 26 } 27 28 bool Start(bool bSuspend = false) { 29 if (bSuspend) 30 SuspendThread(); 31 32 if (this->_threadID == 0) 33 ::pthread_create(&this->_threadID, NULL, _ThreadFunc, this); 34 35 return (this->_threadID != 0); 36 } 37 38 void SuspendThread() { 39 if (this->_flag > 0) { 40 printf("thread has been suspend\n"); 41 return; 42 } 43 __sync_lock_test_and_set((long*) &this->_flag, 1); 44 } 45 46 void Resume() { 47 if (this->_flag > 0) { 48 __sync_lock_test_and_set((long*) &this->_flag, 0); 49 50 ::pthread_mutex_lock(&this->_mutex); 51 ::pthread_cond_broadcast(&this->_cond); 52 ::pthread_mutex_unlock(&this->_mutex); 53 } else 54 printf("thread is running\n"); 55 } 56 57 virtual void OnRun() { 58 while (this->_flag <= 0) { 59 printf("thread running\n"); 60 ::usleep(1000 * 1000); 61 } 62 } 63 64 private: 65 static void *_ThreadFunc(void *param) { 66 Thread *pThis = (Thread*) param; 67 while (true) { 68 /**< suspend = true*/ 69 if (pThis->_flag > 0) { 70 printf("thread suspend\n"); 71 72 ::pthread_mutex_lock(&pThis->_mutex); 73 ::pthread_cond_wait(&pThis->_cond, &pThis->_mutex); 74 ::pthread_mutex_unlock(&pThis->_mutex); 75 76 } else { 77 pThis->OnRun(); 78 79 //pThis->SuspendThread(); 80 } 81 } 82 return NULL; 83 } 84 private: 85 pthread_t _threadID; 86 int _flag; 87 pthread_cond_t _cond; 88 pthread_mutex_t _mutex; 89 }; 90 91 int main(int argc, char *argv[]) { 92 93 char ch; 94 Thread *t = new Thread; 95 t->Start(true); 96 97 while (1) { 98 ::scanf("%c", &ch); 99 switch (ch) { 100 case ‘s‘: 101 t->SuspendThread(); 102 break; 103 case ‘r‘: 104 t->Resume(); 105 break; 106 default: 107 break; 108 } 109 } 110 delete t; 111 112 return 0; 113 }
时间: 2024-10-20 02:59:42