zthread线称队列

#ifndef TQUEUE_HPP #define TQUEUE_HPP #include <deque> #include "zthread/Thread.h" #include "zthread/Condition.h" #include "zthread/Mutex.h" #include "zthread/Guard.h" template<class T> class TQueue { //锁子 ZThread::Mutex lock; //线程协作基类 ZThread::Condition cond; //线程队列元素 std::deque<T> data; public: TQueue() : cond(lock) {} void put(T item) { ZThread::Guard<ZThread::Mutex> g(lock); data.push_back(item); cond.signal(); } T get() { ZThread::Guard<ZThread::Mutex> g(lock); while(data.empty()) cond.wait(); T returnVal = data.front(); data.pop_front(); return returnVal; } }; #endif // TQUEUE_HPP

 

使用双端队列的原因是要这边进去一个线程 那边出去一个线程 在处理的时候,开始都要加上保护锁子

然后处理之

 

#pragma comment(lib,"ZThread_Z.lib") #include <string> #include <iostream> #include "TQueue.h" #include "zthread/Thread.h" #include "LiftOff.h" using namespace ZThread; using namespace std; class LiftOffRunner : public Runnable { TQueue<LiftOff*> rockets; public: void add(LiftOff* lo) { rockets.put(lo); } void run() { try { while(!Thread::interrupted()) { LiftOff* rocket = rockets.get(); rocket->run(); } } catch(Interrupted_Exception&) { /* Exit */ } cout << "Exiting LiftOffRunner" << endl; } }; int main() { try { LiftOffRunner* lor = new LiftOffRunner; Thread t(lor); for(int i = 0; i < 5; i++) lor->add(new LiftOff(10, i)); cin.get(); lor->add(new LiftOff(10, 99)); cin.get(); t.interrupt(); } catch(Synchronization_Exception& e) { cerr << e.what() << endl; } }

这是使用的代码

你可能感兴趣的:(thread,exception,Class)