CubicSDR/src/IOThread.cpp

130 lines
2.6 KiB
C++
Raw Normal View History

2015-07-29 20:57:02 -04:00
#include "IOThread.h"
#include <typeinfo>
2015-07-29 20:57:02 -04:00
std::mutex ReBufferGC::g_mutex;
std::set<ReferenceCounter *> ReBufferGC::garbage;
#define SPIN_WAIT_SLEEP_MS 5
2015-07-29 20:57:02 -04:00
IOThread::IOThread() {
terminated.store(false);
stopping.store(false);
2015-07-29 20:57:02 -04:00
}
IOThread::~IOThread() {
terminated.store(true);
stopping.store(true);
2015-07-29 20:57:02 -04:00
}
#ifdef __APPLE__
void *IOThread::threadMain() {
terminated.store(false);
stopping.store(false);
try {
run();
}
catch (...) {
terminated.store(true);
stopping.store(true);
throw;
}
terminated.store(true);
stopping.store(true);
2015-07-29 20:57:02 -04:00
return this;
};
void *IOThread::pthread_helper(void *context) {
return ((IOThread *) context)->threadMain();
};
#else
void IOThread::threadMain() {
terminated.store(false);
stopping.store(false);
try {
run();
}
catch (...) {
terminated.store(true);
stopping.store(true);
throw;
}
terminated.store(true);
stopping.store(true);
2015-07-29 20:57:02 -04:00
};
#endif
void IOThread::setup() {
//redefined in subclasses
2015-07-29 20:57:02 -04:00
};
void IOThread::run() {
//redefined in subclasses
2015-07-29 20:57:02 -04:00
};
2015-07-29 20:57:02 -04:00
void IOThread::terminate() {
stopping.store(true);
2015-07-29 20:57:02 -04:00
};
2016-01-28 15:49:40 -05:00
void IOThread::onBindOutput(std::string /* name */, ThreadQueueBase* /* threadQueue */) {
2015-07-29 20:57:02 -04:00
};
2016-01-28 15:49:40 -05:00
void IOThread::onBindInput(std::string /* name */, ThreadQueueBase* /* threadQueue */) {
2015-07-29 20:57:02 -04:00
};
void IOThread::setInputQueue(std::string qname, ThreadQueueBase *threadQueue) {
input_queues[qname] = threadQueue;
this->onBindInput(qname, threadQueue);
};
ThreadQueueBase *IOThread::getInputQueue(std::string qname) {
2015-07-29 20:57:02 -04:00
return input_queues[qname];
};
void IOThread::setOutputQueue(std::string qname, ThreadQueueBase *threadQueue) {
output_queues[qname] = threadQueue;
this->onBindOutput(qname, threadQueue);
};
ThreadQueueBase *IOThread::getOutputQueue(std::string qname) {
2015-07-29 20:57:02 -04:00
return output_queues[qname];
};
bool IOThread::isTerminated(int waitMs) {
if (terminated.load()) {
return true;
}
else if (waitMs == 0) {
return false;
}
//this is a stupid busy plus sleep loop
int nbCyclesToWait = 0;
if (waitMs < 0) {
nbCyclesToWait = std::numeric_limits<int>::max();
}
else {
nbCyclesToWait = (waitMs / SPIN_WAIT_SLEEP_MS) + 1;
}
for ( int i = 0; i < nbCyclesToWait; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(SPIN_WAIT_SLEEP_MS));
if (terminated.load()) {
return true;
}
}
std::cout << "ERROR: thread '" << typeid(*this).name() << "' has not terminated in time ! (> " << waitMs << " ms)" << std::endl;
2015-07-29 20:57:02 -04:00
return terminated.load();
2016-01-28 15:49:40 -05:00
}