Improve Document::lock() with an enum as parameter instead of a bool.

This commit is contained in:
David Capello 2011-03-27 00:15:08 -03:00
parent eee8e17fcf
commit a21d15b4ef
3 changed files with 33 additions and 25 deletions

View File

@ -422,27 +422,30 @@ SpriteImpl* SpriteImpl::copyLayers(SpriteImpl* dst_sprite, const SpriteImpl* src
//////////////////////////////////////////////////////////////////////
// Multi-threading ("sprite wrappers" use this)
bool Document::lock(bool write)
bool Document::lock(LockType lockType)
{
ScopedLock lock(*m_mutex);
// read-only
if (!write) {
// If no body is writting the sprite...
if (!m_write_lock) {
// We can read it
++m_read_locks;
return true;
}
}
// read and write
else {
// If no body is reading and writting...
if (m_read_locks == 0 && !m_write_lock) {
// We can start writting the sprite...
m_write_lock = true;
return true;
}
switch (lockType) {
case ReadLock:
// If no body is writting the sprite...
if (!m_write_lock) {
// We can read it
++m_read_locks;
return true;
}
break;
case WriteLock:
// If no body is reading and writting...
if (m_read_locks == 0 && !m_write_lock) {
// We can start writting the sprite...
m_write_lock = true;
return true;
}
break;
}
return false;

View File

@ -59,6 +59,11 @@ class Document
{
public:
enum LockType {
ReadLock,
WriteLock
};
// Creates a document with one sprite, with one transparent layer,
// and one frame.
static Document* createBasicDocument(int imgtype, int width, int height, int ncolors);
@ -145,9 +150,9 @@ public:
//////////////////////////////////////////////////////////////////////
// Multi-threading ("sprite wrappers" use this)
// Lock the sprite to read or write it, returning true if the sprite
// can be accessed in the desired mode.
bool lock(bool write);
// Locks the sprite to read or write on it, returning true if the
// sprite can be accessed in the desired mode.
bool lock(LockType lockType);
// If you've locked the sprite to read, using this method you can
// raise your access level to write it.

View File

@ -82,14 +82,14 @@ public:
explicit DocumentReader(Document* document)
: DocumentWrapper(document)
{
if (m_document && !m_document->lock(false))
if (m_document && !m_document->lock(Document::ReadLock))
throw LockedDocumentException();
}
explicit DocumentReader(const DocumentReader& copy)
: DocumentWrapper(copy)
{
if (m_document && !m_document->lock(false))
if (m_document && !m_document->lock(Document::ReadLock))
throw LockedDocumentException();
}
@ -102,7 +102,7 @@ public:
DocumentWrapper::operator=(copy);
// relock the document
if (m_document && !m_document->lock(false))
if (m_document && !m_document->lock(Document::ReadLock))
throw LockedDocumentException();
return *this;
@ -134,7 +134,7 @@ public:
, m_locked(false)
{
if (m_document) {
if (!m_document->lock(true))
if (!m_document->lock(Document::WriteLock))
throw LockedDocumentException();
m_locked = true;