File - locking

- Made locking an integral part of the File object, so that a client
  may now call File::lock multiple times with no effect beyond the first
  call.  This simplifies situations like the 'cal' command that must scan
  for recurrence changes, modify tasks, then optionally run a second
  report, all without locking issues.
This commit is contained in:
Paul Beckingham 2011-08-14 11:54:53 -04:00
parent 1f58856299
commit 9a862bc75a
2 changed files with 20 additions and 1 deletions

View file

@ -42,6 +42,7 @@ File::File ()
: Path::Path () : Path::Path ()
, fh (NULL) , fh (NULL)
, h (-1) , h (-1)
, locked (false)
{ {
} }
@ -50,6 +51,7 @@ File::File (const Path& other)
: Path::Path (other) : Path::Path (other)
, fh (NULL) , fh (NULL)
, h (-1) , h (-1)
, locked (false)
{ {
} }
@ -58,6 +60,7 @@ File::File (const File& other)
: Path::Path (other) : Path::Path (other)
, fh (NULL) , fh (NULL)
, h (-1) , h (-1)
, locked (false)
{ {
} }
@ -66,6 +69,7 @@ File::File (const std::string& in)
: Path::Path (in) : Path::Path (in)
, fh (NULL) , fh (NULL)
, h (-1) , h (-1)
, locked (false)
{ {
} }
@ -82,6 +86,7 @@ File& File::operator= (const File& other)
if (this != &other) if (this != &other)
Path::operator= (other); Path::operator= (other);
locked = false;
return *this; return *this;
} }
@ -117,6 +122,7 @@ bool File::open ()
if (fh) if (fh)
{ {
h = fileno (fh); h = fileno (fh);
locked = false;
return true; return true;
} }
} }
@ -138,6 +144,7 @@ void File::close ()
fclose (fh); fclose (fh);
fh = NULL; fh = NULL;
h = -1; h = -1;
locked = false;
} }
} }
@ -152,17 +159,28 @@ bool File::lock ()
; ;
if (retry <= 3) if (retry <= 3)
{
locked = true;
return true; return true;
}
} }
locked = false;
return false; return false;
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
bool File::waitForLock () bool File::waitForLock ()
{ {
if (locked)
return true;
if (fh && h != -1) if (fh && h != -1)
return flock (h, LOCK_EX) == 0 ? true : false; if (flock (h, LOCK_EX) == 0)
{
locked = true;
return true;
}
return false; return false;
} }

View file

@ -82,6 +82,7 @@ public:
private: private:
FILE* fh; FILE* fh;
int h; int h;
bool locked;
}; };
#endif #endif