Chris@297: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ Chris@297: Chris@297: /* Chris@297: Sonic Visualiser Chris@297: An audio file viewer and annotation editor. Chris@297: Centre for Digital Music, Queen Mary, University of London. Chris@297: This file copyright 2007 QMUL. Chris@297: Chris@297: This program is free software; you can redistribute it and/or Chris@297: modify it under the terms of the GNU General Public License as Chris@297: published by the Free Software Foundation; either version 2 of the Chris@297: License, or (at your option) any later version. See the file Chris@297: COPYING included with this distribution for more information. Chris@297: */ Chris@297: Chris@297: #include "Serialiser.h" Chris@1857: #include "Debug.h" Chris@297: Chris@406: #include Chris@406: Chris@297: QMutex Chris@297: Serialiser::m_mapMutex; Chris@297: Chris@297: std::map Chris@297: Serialiser::m_mutexMap; Chris@297: Chris@297: Serialiser::Serialiser(QString id) : Chris@1857: Serialiser(id, nullptr) { } Chris@1857: Chris@1857: Serialiser::Serialiser(QString id, const std::atomic *cancelled) : Chris@1857: m_id(id), Chris@1857: m_cancelled(cancelled), Chris@1857: m_locked(false) Chris@297: { Chris@297: m_mapMutex.lock(); Chris@297: Chris@297: if (m_mutexMap.find(m_id) == m_mutexMap.end()) { Chris@297: m_mutexMap[m_id] = new QMutex; Chris@297: } Chris@297: Chris@406: // The id mutexes are never deleted, so once we have a reference Chris@406: // to the one we need, we can hold on to it while we release the Chris@406: // map mutex. We need to release the map mutex, otherwise if the Chris@406: // id mutex is currently held, it will never be released (because Chris@406: // the destructor needs to hold the map mutex to release the id Chris@406: // mutex). Chris@406: Chris@406: QMutex *idMutex = m_mutexMap[m_id]; Chris@398: Chris@297: m_mapMutex.unlock(); Chris@406: Chris@1857: if (!m_cancelled) { Chris@1857: idMutex->lock(); Chris@1857: m_locked = true; Chris@1857: } else { Chris@1857: // try to lock, polling the cancelled status occasionally Chris@1857: while (!m_locked && ! *m_cancelled) { Chris@1857: m_locked = idMutex->tryLock(500); Chris@1857: if (*m_cancelled) { Chris@1857: SVCERR << "Serialiser: cancelled!" << endl; Chris@1857: } Chris@1857: } Chris@1857: } Chris@297: } Chris@297: Chris@297: Serialiser::~Serialiser() Chris@297: { Chris@398: m_mapMutex.lock(); Chris@1857: Chris@1857: if (m_locked) { Chris@1857: m_mutexMap[m_id]->unlock(); Chris@1857: } Chris@398: Chris@398: m_mapMutex.unlock(); Chris@297: } Chris@297: Chris@297: Chris@297: