1. Inheriting and overriding the Run method
We encapsulate the thread class and set the member function run () as a pure virtual function, so we use class inheritance and override the Run method:
classInccount: PublicThread//Increase Count Thread{ Private: intid_; Public: Inccount (intID): id_ (ID) {}voidrun () { for(intI=0; I <Ten; i + +) {{MutexlockguardLock(mutex); Count++; if(Count = = A) {cond.notify ();//Notice } //Print information for easy commissioningstd::cout<<"Thread:"<<id_<<"Count:"<< Count <<Std::endl; }//critical SectionSleep1.5);//Note: Sleep is not a synchronous primitive, just for debugging purposes } }};classWatchcount: PublicThread//Monitoring Threads{ Private: intid_; Public: Watchcount (intID): id_ (ID) {}voidrun () {MutexlockguardLock(mutex);//Locking while(Count < A)//here with while to prevent false wakeup{cond.wait (); } Assert (Count>= A); Count+= the; Std::cout<<"Thread:"<<id_<<"Count:"<< Count <<Std::endl; }};
If you use polymorphism, you can vector save the parent pointer, and initialize the reference to the subclass, but using us is vector<Thread*> often confused, that is, vector as a variable on the stack, its program end variable lifetime end,
The object that the pointer in the container points to requires us to go manually, which makes it delete prone to error.
shared_ptr (C++11 has been added to STD) in the Boost library avoids this memory leak error: The end of thevector lifetime, the shared_ptr release, the object's reference count becomes 0, and the resource is freed automatically.
#include"Thread.h"#include"MutexLock.h"#include"Condition.h"#include<vector>#include<memory>using namespacestd; Mutexlock Mutex;//Mutual exclusion LockCondition cond (mutex);//condition VariableintCount =0;intmain () {vector< shared_ptr<thread> > t (3); t[0].reset (NewWatchcount (1)); t[1].reset (NewInccount (2)); t[2].reset (NewInccount (3)); for(intI=0;i<3; i++) {T[i]-start (); } for(intI=0;i<3; i++) {T[i]-join (); } } return 0;}
C + + Package line Libraries 3