zthread线程的协作

ztrehead中线程协作的基类是condition  —_—

在处理的时候 可以通过wait挂起任务 通过signal唤醒任务 或者是broadcast

 

#pragma comment(lib,"ZThread_Z.lib") #include <iostream> #include <string> #include "zthread/Thread.h" #include "zthread/Mutex.h" #include "zthread/Guard.h" #include "zthread/Condition.h" #include "zthread/ThreadedExecutor.h" using namespace ZThread; using namespace std; class Car { //锁子 Mutex lock; // the base of trehad cooperation Condition condition; //flag for wax bool waxOn; public: Car() : condition(lock), waxOn(false) {} //lock nad not wax //waxing void waxed() { Guard<Mutex> g(lock); waxOn = true; // Ready to buff condition.signal(); } //liggting void buffed() { Guard<Mutex> g(lock); waxOn = false; // Ready for another coat of wax //weaken condition.signal(); } void waitForWaxing() { Guard<Mutex> g(lock); while(waxOn == false) condition.wait(); } void waitForBuffing() { Guard<Mutex> g(lock); while(waxOn == true) condition.wait(); } }; class WaxOn : public Runnable { CountedPtr<Car> car; public: WaxOn(CountedPtr<Car>& c) : car(c) {} void run() { try { while(!Thread::interrupted()) { cout << "Wax On!" << endl; Thread::sleep(2); car->waxed(); car->waitForBuffing(); } } catch(Interrupted_Exception& ) { cout << "Ending Wax On process" << endl; } } }; class WaxOff : public Runnable { CountedPtr<Car> car; public: WaxOff(CountedPtr<Car>& c) : car(c) {} void run() { try { while(!Thread::interrupted()) { car->waitForWaxing(); cout << "Wax Off!" << endl; Thread::sleep(200); car->buffed(); } } catch(Interrupted_Exception&) { /* Exit */ } cout << "Ending Wax Off process" << endl; } }; int main() { cout << "Press <Enter> to quit" << endl; try { CountedPtr<Car> car(new Car); ThreadedExecutor executor; executor.execute(new WaxOff(car)); executor.execute(new WaxOn(car)); cin.get(); executor.interrupt(); } catch(Synchronization_Exception& e) { cerr << e.what() << endl; } }

 

感觉就是这样使用的

 

基本的任务

class task

 

class Step1: public Runnable

{

CountedPtr<task> task_;

 

class Step2: public Runnable

{

CountedPtr<task> task_;

 

你可能感兴趣的:(thread,c,exception,Class,任务,Signal)