1 //============================================================================2 //Name:thread.cpp3 //Author:littleku4 //Version:5 //Copyright:littleku6 //Description:thread in C + +, Ansi-style7 //============================================================================8 9#include <pthread.h>Ten#include <unistd.h> One#include <stdio.h> A - using namespacestd; - the classThread { - Public: - Thread () { - This->_flag =0; + This->_threadid =0; -::p Thread_mutex_init (& This-_mutex, NULL); +::p Thread_cond_init (& This-_cond, NULL); A } at Virtual~Thread () { -::p Thread_mutex_destroy (& This-_mutex); -::p Thread_cond_destroy (& This-_cond); - } - - BOOLStart (BOOLBsuspend =false) { in if(bsuspend) - SuspendThread (); to + if( This->_threadid = =0) -::p thread_create (& This->_threadid, NULL, _threadfunc, This); the * return( This->_threadid! =0); $ }Panax Notoginseng - voidSuspendThread () { the if( This->_flag >0) { +printf"thread has been suspend\n"); A return; the } +__sync_lock_test_and_set ((Long*) & This->_flag,1); - } $ $ voidResume () { - if( This->_flag >0) { -__sync_lock_test_and_set ((Long*) & This->_flag,0); the -::p Thread_mutex_lock (& This-_mutex);Wuyi::p thread_cond_broadcast (& This-_cond); the::p Thread_mutex_unlock (& This-_mutex); -}Else Wuprintf"thread is running\n"); - } About $ Virtual voidOnRun () { - while( This->_flag <=0) { -printf"Thread running\n"); -:: Usleep ( +* +); A } + } the - Private: $ Static void*_threadfunc (void*param) { theThread *pthis = (thread*) param; the while(true) { the /**< suspend = True*/ the if(Pthis->_flag >0) { -printf"Thread suspend\n"); in the::p Thread_mutex_lock (&pThis->_mutex); the::p thread_cond_wait (&pthis->_cond, &pThis->_mutex); About::p Thread_mutex_unlock (&pThis->_mutex); the the}Else { thePthis->OnRun (); + - //Pthis->suspendthread (); the }Bayi } the returnNULL; the } - Private: - pthread_t _threadid; the int_flag; the pthread_cond_t _cond; the pthread_mutex_t _mutex; the }; - the intMainintargcChar*argv[]) { the the Charch;94Thread *t =NewThread; theT->start (true); the the while(1) {98:: scanf ("%c", &ch); About Switch(CH) { - Case 's':101T->SuspendThread ();102 Break;103 Case 'R':104T->Resume (); the Break;106 default:107 Break;108 }109 } the DeleteT;111 the return 0;113}
Linux thread suspend recovery