Skip to content

Commit a1ad21e

Browse files
authored
Merge pull request #79 from jviereck/jviereck/tracer_logging
Tracer: Adding lock to make it threadsafe
2 parents e673795 + 18460a5 commit a1ad21e

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

include/dynamic-graph/tracer.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <boost/function.hpp>
99
#include <list>
1010
#include <string>
11+
#include <mutex>
1112

1213
#include <dynamic-graph/entity.h>
1314
#include <dynamic-graph/exception-traces.h>
@@ -27,6 +28,7 @@ class DG_TRACER_DLLAPI Tracer : public Entity {
2728
protected:
2829
typedef std::list<const SignalBase<int> *> SignalList;
2930
SignalList toTraceSignals;
31+
std::mutex files_mtx;
3032

3133
public:
3234
enum TraceStyle {

src/traces/tracer-real-time.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ void TracerRealTime::openFile(const SignalBase<int> &sig,
146146

147147
void TracerRealTime::closeFiles() {
148148
dgDEBUGIN(15);
149+
std::lock_guard<std::mutex> files_lock(files_mtx);
149150

150151
FileList::iterator iter = files.begin();
151152
HardFileList::iterator hardIter = hardFiles.begin();

src/traces/tracer.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ void Tracer::openFile(const SignalBase<int> &sig, const string &givenname) {
171171

172172
void Tracer::closeFiles() {
173173
dgDEBUGIN(15);
174+
std::lock_guard<std::mutex> files_lock(files_mtx);
174175

175176
for (FileList::iterator iter = files.begin(); files.end() != iter; ++iter) {
176177
std::ostream *filePtr = *iter;
@@ -193,6 +194,14 @@ void Tracer::record() {
193194

194195
dgDEBUGIN(15);
195196

197+
// Ensure record() never hangs. If the attempt to acquire the lock fails,
198+
// then closeFiles() is active and we shouldn't write to files anyways.
199+
std::unique_lock<std::mutex> files_lock(files_mtx, std::try_to_lock);
200+
if (!files_lock.owns_lock()) {
201+
dgDEBUGOUT(15);
202+
return;
203+
}
204+
196205
if (files.size() != toTraceSignals.size()) {
197206
DG_THROW
198207
ExceptionTraces(ExceptionTraces::NOT_OPEN, "No files open for tracing",

0 commit comments

Comments
 (0)