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.

Qt Code:
  1. class Sync {
  2. public:
  3. Sync(const QString &key) : mem(key){
  4. dat = 0;
  5. if(mem.create(sizeof(bool))) dat = (bool*)mem.data();
  6. else return;
  7. mem.lock();
  8. *dat = true;
  9. mem.unlock();
  10. }
  11. ~Sync() { if(dat) mem.detach(); }
  12. bool tryLock() {
  13. mem.lock();
  14. if(*dat) {
  15. /* lock the real resource here */;
  16. *dat = false;
  17. mem.unlock();
  18. return true;
  19. } else { mem.unlock(); return false; }
  20. }
  21. void lock() {
  22. mem.lock();
  23. if(*dat) { /* lock the resource, etc. */ } else {
  24. mem.unlock();
  25. // lock on a QSystemSemaphore
  26. }
  27. }
  28. // unlock in a similar fashion
  29. private:
  30. QSharedMemory mem;
  31. bool *dat;
  32. }
To copy to clipboard, switch view to plain text mode 

This is ALMOST foul proof.