00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00025 #include "ShareLock.h"
00026
00027 utils::ShareLock::ShareLock() {
00028 pthread_mutex_init(&mut, NULL);
00029 pthread_cond_init(&cond, NULL);
00030 };
00031
00032 utils::ShareLock::~ShareLock() {
00033 pthread_mutex_destroy(&mut);
00034 pthread_cond_destroy(&cond);
00035 };
00036
00037 inline void utils::ShareLock::alloc(const string &res, bool ex) {
00038 if(ex)
00039 excl.insert(res);
00040 else
00041 shared.insert(res);
00042 };
00043
00044 inline void utils::ShareLock::free(const string &res) {
00045 if(shared.count(res)==0)
00046 excl.erase(res);
00047 else
00048 shared.erase(res);
00049 };
00050
00051 inline bool utils::ShareLock::isbusy(const string &res, bool ex) {
00052 return excl.count(res)!=0 || (ex && (shared.count(res)!=0) );
00053 };
00054
00055 void utils::ShareLock::lock(const string &resource, bool ex=false) {
00056 pthread_mutex_lock(&mut);
00057 while(isbusy(resource, ex))
00058 pthread_cond_wait(&cond, &mut);
00059 alloc(resource, ex);
00060 pthread_mutex_unlock(&mut);
00061 };
00062
00063 void utils::ShareLock::unlock(const string &resource) {
00064 pthread_mutex_lock(&mut);
00065 free(resource);
00066 pthread_cond_broadcast(&cond);
00067 pthread_mutex_unlock(&mut);
00068 };
00069