zthread学习 实例六 访问控制

就是对共享资源的同步访问,以免造成不确定的状态。

Zhread库是基于Mutex临界区来组建同步机制的。

#include "stdafx.h" #include <iostream> #include <fstream> #include "zthread/Guard.h" #include "zthread/Mutex.h" #include "zthread/ThreadedExecutor.h" #include "zthread/Cancelable.h" #include "zthread/Runnable.h" #include "zthread/Thread.h" using namespace ZThread; using namespace std; //用于共享资源的虚基类, class Generator : public Cancelable { public: Generator(): canceled(false){} virtual int nextValue() = 0; void cancel() {canceled = true;} bool isCanceled(){return canceled;} private: bool canceled; }; //实现基类的虚函数nextValue() class EvenGenerator : public Generator { public: EvenGenerator() { currentEvenValue = 0; } ~EvenGenerator() { cout << "~EvenGenerator" << endl; } int nextValue() { Guard<Mutex> g(Lock); //同步控制 currentEvenValue++; Thread::yield(); //放大因线程调度问题产生的不一致 currentEvenValue++; return currentEvenValue; } private: unsigned int currentEvenValue; Mutex Lock; }; //任务类,重点run()函数 class EvenChecker : public Runnable { public: EvenChecker(const CountedPtr<Generator>& g, int idn): pGenerator(g), id(idn){} ~EvenChecker() { cout << "~EvenChecker" << id <<endl; } void run() { while (!pGenerator->isCanceled()) //检查任务共享资源是否已退出,通过控制共享资源来控制所有创建的任务是否需要返回 { int val = pGenerator->nextValue(); if (val % 2 != 0) { cout << val << " not even!" <<endl; pGenerator->cancel(); //共享资源退出 } else { cout <<"ID: "<<id << ", value = " << val<<endl; Thread::sleep(200); } } } template<typename GenType> static void test(int n = 5) { try { ThreadedExecutor executor; CountedPtr<Generator> pGp(new GenType); for (int i = 0; i < n; i++) { executor.execute(new EvenChecker(pGp, i)); //引用同一个Generator,多个任务共享 } } catch (Synchronization_Exception& e) { cerr << e.what() << endl; } } private: CountedPtr<Generator> pGenerator; int id; }; int _tmain(int argc, _TCHAR* argv[]) { try { EvenChecker::test<EvenGenerator>(); } catch (Synchronization_Exception& e) { cerr << e.what() <<endl; } cin.get(); return 0; }

Guard<>模板很方便的定义了同步机制,它在创建时用acquire()来获得一个Lockable对象,被销毁时用release()来释放这个锁。Guard对象的创建很好的利用了变量作用域概念。例如:

 

void fun()

{

      ... ...

      {    //特意添加的用于控制Guard作用域的括号

            Guard<Mutex> g(Lock);

            ... ...//重点临界区代码

       }

}

 

Zhread库中给Guard<>提供了4种类型的锁策略:

1、CompoundScope

     Note: Locking policy that aggregates two policies that share a target.It is not appropriate to use with any type of OverlappedScope

 

2、LockedScope(默认)

     Note: Locking policy for Lockable objects. This policy acquire()s a Lockable when the protection scope is created, and it release()s a Lockable when the scope is destroyed.

 

3、UnlockedScope(解锁)

     Note: Locking policy for Lockable objects. This policy release()s a Lockable when the protection scope is created, and it acquire()s a Lockable when the scope is destroyed.

4、TimedLockedScope(带时间)

      Note:  Locking policy that attempts to enterScope some resource in a certain amount of time using an tryEnterScope-relase protocol.

 

5、OverlappedScope

    Note:  Locking policy allows the effective scope of two locks to overlap by releasing and disabling one lock before its Guard does so.

你可能感兴趣的:(zthread学习 实例六 访问控制)