// File: example.cpp // // Copyright (c) 2003 // Kevin Atkinson // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without // fee, provided that the above copyright notice appear in all copies // and that both that copyright notice and this permission notice // appear in supporting documentation. Kevin Atkinson makes no // representations about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. // // Lock Example #include "lock.hpp" using namespace distribnet; class MultithreadedObject { public: void init(); void sync(); private: void setup(LockState); void modify1(WillOnlyLock); void modify2(WillOnlyLock); void modify3(WillOnlyLock); void synchronize(WillLock); void network_function(WillUnlock); MultithreadedObject() : counter(0), var1(10), var2(20) {} int counter; int var1; int var2; Mutex lock; }; void MultithreadedObject::init() { { LOCK(lock); // will automaticlly unlock at the end of the scope counter = 0; var1 = var2 = 99; setup(lock); } // now do things that don't need the lock } void MultithreadedObject::sync() { synchronize(lock); // simply pass in the lock. The lock classes will // take care of the rest } void MultithreadedObject::setup(LockState l) // will simply pass the lock state around to other functions that may // lock or unlock { modify1(l); synchronize(l); } void MultithreadedObject::modify1(WillOnlyLock) // If not locked will lock when the function is called and unlock // when the function returns. Will not unlock otherwise. { var1 = 111; } void MultithreadedObject::modify2(WillOnlyLock) { var2 = 222; } void MultithreadedObject::modify3(WillOnlyLock) { var2 = 333; } void MultithreadedObject::synchronize(WillLock l) // If not locked will lock when the function is called and unlock // when the function returns. But is allowed to also Unlock the // mutex inside the function. { modify2(l); network_function(l); // this is ok becuase I am allowed to unlock modify3(l); } void MultithreadedObject::network_function(WillUnlock) // If locked will unlock when the function is called and lock when the // function returns. Also allowed to lock in the middle of the // function. { // use network functions which may block for a long time }