Create a protected resource that will determine if the resource you are after is available. Then regular lock() is fine because you only do the locking for a short moment.
class Sync {
public:
Sync
(const QString &key
) : mem
(key
){ dat = 0;
if(mem.create(sizeof(bool))) dat = (bool*)mem.data();
else return;
mem.lock();
*dat = true;
mem.unlock();
}
~Sync() { if(dat) mem.detach(); }
bool tryLock() {
mem.lock();
if(*dat) {
/* lock the real resource here */;
*dat = false;
mem.unlock();
return true;
} else { mem.unlock(); return false; }
}
void lock() {
mem.lock();
if(*dat) { /* lock the resource, etc. */ } else {
mem.unlock();
// lock on a QSystemSemaphore
}
}
// unlock in a similar fashion
private:
QSharedMemory mem;
bool *dat;
}
class Sync {
public:
Sync(const QString &key) : mem(key){
dat = 0;
if(mem.create(sizeof(bool))) dat = (bool*)mem.data();
else return;
mem.lock();
*dat = true;
mem.unlock();
}
~Sync() { if(dat) mem.detach(); }
bool tryLock() {
mem.lock();
if(*dat) {
/* lock the real resource here */;
*dat = false;
mem.unlock();
return true;
} else { mem.unlock(); return false; }
}
void lock() {
mem.lock();
if(*dat) { /* lock the resource, etc. */ } else {
mem.unlock();
// lock on a QSystemSemaphore
}
}
// unlock in a similar fashion
private:
QSharedMemory mem;
bool *dat;
}
To copy to clipboard, switch view to plain text mode
This is ALMOST foul proof.
Bookmarks