例一、生产者-消费者 一个任务制作烤面包(生产者),一个任务给烤面包抹黄油(消费者),还有一个任务是往抹好黄油的烤面包上抹果酱(消费者)。 代码如下: #include "stdafx.h" #include "zthread/FastMutex.h" #include "zthread/CountedPtr.h" #include "zthread/Runnable.h" #include "zthread/Condition.h" #include <iostream> using namespace ZThread; using namespace std; class Jammer : public Runnable { public: Jammer() : butteredToastReady(Lock), jammed(0), isGotButteredToast(false){} void moreButteredToastReady() { Guard<Mutex> g(Lock); isGotButteredToast = true; butteredToastReady.signal(); } void run() { try { while (!Thread::interrupted()) { { Guard<Mutex> g(Lock); while (isGotButteredToast == false) butteredToastReady.wait(); ++jammed; } cout << "Putting jam on toast : " <<jammed <<endl; { Guard<Mutex> g(Lock); isGotButteredToast = false; } } } catch (Interrupted_Exception& e) { cout << " Jarry : "<< e.what() <<endl; } } private: Mutex Lock; Condition butteredToastReady; bool isGotButteredToast; int jammed; }; class Butterer : public Runnable { public: Butterer(CountedPtr<Jammer>& j) : toastReady(Lock), jammer(j), Buttered(0), isGotToast(false){} void moreToastReady() { Guard<Mutex> g(Lock); isGotToast = true; toastReady.signal(); } void run() { try { while (!Thread::interrupted()) { { Guard<Mutex> g(Lock); while (!isGotToast) toastReady.wait(); ++Buttered; } cout << "Buttering toast :" << Buttered <<endl; jammer->moreButteredToastReady(); { Guard<Mutex> g(Lock); isGotToast = false; } } } catch (Interrupted_Exception& e) { cout << " Jarry " << e.what() << endl; } } private: Mutex Lock; Condition toastReady; CountedPtr<Jammer> jammer; bool isGotToast; int Buttered; }; class Toast : public Runnable { public: Toast(CountedPtr<Butterer>& aButterer) : butterer(aButterer), toasted(0) {} void run() { try { while (!Thread::interrupted()) { Thread::sleep(1000); cout << "A new Toa