Serialiser.cpp
Go to the documentation of this file.
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2 
3 /*
4  Sonic Visualiser
5  An audio file viewer and annotation editor.
6  Centre for Digital Music, Queen Mary, University of London.
7  This file copyright 2007 QMUL.
8 
9  This program is free software; you can redistribute it and/or
10  modify it under the terms of the GNU General Public License as
11  published by the Free Software Foundation; either version 2 of the
12  License, or (at your option) any later version. See the file
13  COPYING included with this distribution for more information.
14 */
15 
16 #include "Serialiser.h"
17 #include "Debug.h"
18 
19 #include <iostream>
20 
21 QMutex
23 
24 std::map<QString, QMutex *>
26 
28  Serialiser(id, nullptr) { }
29 
30 Serialiser::Serialiser(QString id, const std::atomic<bool> *cancelled) :
31  m_id(id),
32  m_cancelled(cancelled),
33  m_locked(false)
34 {
35  m_mapMutex.lock();
36 
37  if (m_mutexMap.find(m_id) == m_mutexMap.end()) {
38  m_mutexMap[m_id] = new QMutex;
39  }
40 
41  // The id mutexes are never deleted, so once we have a reference
42  // to the one we need, we can hold on to it while we release the
43  // map mutex. We need to release the map mutex, otherwise if the
44  // id mutex is currently held, it will never be released (because
45  // the destructor needs to hold the map mutex to release the id
46  // mutex).
47 
48  QMutex *idMutex = m_mutexMap[m_id];
49 
50  m_mapMutex.unlock();
51 
52  if (!m_cancelled) {
53  idMutex->lock();
54  m_locked = true;
55  } else {
56  // try to lock, polling the cancelled status occasionally
57  while (!m_locked && ! *m_cancelled) {
58  m_locked = idMutex->tryLock(500);
59  if (*m_cancelled) {
60  SVCERR << "Serialiser: cancelled!" << endl;
61  }
62  }
63  }
64 }
65 
67 {
68  m_mapMutex.lock();
69 
70  if (m_locked) {
71  m_mutexMap[m_id]->unlock();
72  }
73 
74  m_mapMutex.unlock();
75 }
76 
77 
78 
static QMutex m_mapMutex
Definition: Serialiser.h:56
QString m_id
Definition: Serialiser.h:53
~Serialiser()
Release the lock associated with the given id (if taken, rather than cancelled).
Definition: Serialiser.cpp:66
const std::atomic< bool > * m_cancelled
Definition: Serialiser.h:54
static std::map< QString, QMutex * > m_mutexMap
Definition: Serialiser.h:57
bool m_locked
Definition: Serialiser.h:55
#define SVCERR
Definition: Debug.h:109
Serialiser(QString id)
Construct a serialiser that takes the lock associated with the given id.
Definition: Serialiser.cpp:27