zthread学习 实例十一 信号量机制

ZThread库提供了另外一种同步机制——信号量,它定义了两种信号量:Semaphore(带上界) 和 CountingSemaphore(不带上界),都类似于传统的信号量,下面例子说明了其用法:

#include "stdafx.h" #include "Display.h" #include <iostream> using namespace std; using namespace ZThread; class Reads : public Runnable { public: Reads(CountedPtr<Semaphore>/*CountedPtr<CountingSemaphore>*/& aSemaphore, CountedPtr<Display>& disp, int idn = -1): id(idn), pSemaphore(aSemaphore), pDisplay(disp){} void run() { try { while (!Thread::interrupted()) { //信号量减1 pSemaphore->acquire(); output(" ,Jarry Reading..."); Thread::sleep(1000); //信号量增1 pSemaphore->release(); } } catch (Interrupted_Exception& e) { cerr << "Jarry " << e.what() << endl; } catch (InvalidOp_Exception& e) //越界,结束该线程 { cerr << "Jarry " << e.what() << endl; return; } } //同步输出 void output(string str) { ostringstream os; os << *this << " : " << str <<endl; pDisplay->OutPut(os); } friend ostream& operator<< (ostream& os, Reads& reads) { return os << "id: " << reads.id << " Count = " << reads.pSemaphore->count(); } private: int id; CountedPtr<Semaphore> pSemaphore; //CountedPtr<CountingSemaphore> pSemaphore; CountedPtr<Display> pDisplay; }; int main() { //创建一个count为5信号量,当count计数达到上界时,就会抛出InvalidOp_Exception异常 CountedPtr<Semaphore> pSemaphore(new Semaphore(5, 2)); //类似Semaphore,只是没有一个上界,不会抛出InvalidOp_Exception异常 //CountedPtr<CountingSemaphore>pSemaphore(new CountingSemaphore(5)); CountedPtr<Display> display(new Display); ThreadedExecutor executor; for (int i = 0; i < 20; i ++) { //这样测试是为了有在创建线程之前有线程执行,并且能促使信号量增1 executor.wait(1500); executor.execute(new Reads(pSemaphore, display, i)); } cin.get(); executor.interrupt(); cin.get(); return 0; }  

运行结果:

zthread学习 实例十一 信号量机制_第1张图片

 

其中同步显示类,好像还没有贴出来,暂且贴在些吧:

#ifndef DISPLAY_H #define DISPLAY_H #include <iostream> #include <sstream> using namespace ZThread; using namespace std; class Display { public: void OutPut(ostringstream& os) { Guard<Mutex> g(Lock); cout<<os.str(); } private: Mutex Lock; }; #endif 

你可能感兴趣的:(thread,exception,String,Semaphore,OS,output)