void TestPointer::multiRef(int count) { QAtomicInt counter; PointerClass * ptrClass = new PointerClass(counter); QList<Pointer<PointerClass> > ptrList; QVERIFY(counter.fetchAndAddOrdered(0) == 1); // Create pointer for(int i = 0; i < count; i++) { ptrList.append(Pointer<PointerClass>(ptrClass)); QVERIFY(ptrList.last() != 0); QVERIFY(counter.fetchAndAddOrdered(0) == 1); QVERIFY(ptrList.last()->testFunc()); } // Remove pointer (all but one) for(int i = count - 1; i > 0; i--) { ptrList.removeLast(); QVERIFY(ptrList.last() != 0); QVERIFY(counter.fetchAndAddOrdered(0) == 1); QVERIFY(ptrList.last()->testFunc()); } Pointer<PointerClass> ptr(ptrList.takeLast()); ptr = 0; QVERIFY(ptr == 0); QVERIFY(counter.fetchAndAddOrdered(0) == 0); }
void CallbackObject::Run(void) { // start the run loop if (gAdminRunLoopRunning.fetchAndAddOrdered(0)) CFRunLoopRun(); // if it exits, schedule it to start again. This usually means there is nothing // setup using a callback, so don't waste cycles and wait a while before restarting. if (gAdminRunLoopRunning.fetchAndAddOrdered(0)) QTimer::singleShot(100, Qt::CoarseTimer, this, SLOT(Run())); }
void TestPointer::single() { QAtomicInt counter; Pointer<PointerClass> ptr(new PointerClass(counter)); QVERIFY(ptr != 0); QVERIFY(counter.fetchAndAddOrdered(0) == 1); QVERIFY(ptr->testFunc()); ptr = 0; QVERIFY(ptr == 0); QVERIFY(counter.fetchAndAddOrdered(0) == 0); }
/// \brief Expire any clients in the delete list void LogForwardThread::expireClients(void) { #ifndef NOLOGSERVER QMutexLocker lock(&logClientMapMutex); QMutexLocker lock2(&logRevClientMapMutex); QMutexLocker lock3(&logClientToDelMutex); while (!logClientToDel.isEmpty()) { QString clientId = logClientToDel.takeFirst(); logClientCount.deref(); LOG(VB_GENERAL, LOG_INFO, QString("Expiring client %1 (#%2)") .arg(clientId).arg(logClientCount.fetchAndAddOrdered(0))); LoggerListItem *item = logClientMap.take(clientId); if (!item) continue; LoggerList *list = item->list; delete item; while (!list->isEmpty()) { LoggerBase *logger = list->takeFirst(); ClientList *clientList = logRevClientMap.value(logger, NULL); if (!clientList || clientList->size() == 1) { if (clientList) { logRevClientMap.remove(logger); delete clientList; } delete logger; continue; } clientList->removeAll(clientId); } delete list; } // TODO FIXME: This is not thread-safe! // just this daemon left if (logClientCount.fetchAndAddOrdered(0) == 1 && m_shutdownTimer && !m_shutdownTimer->isActive()) { LOG(VB_GENERAL, LOG_INFO, "Starting 5min shutdown timer"); m_shutdownTimer->start(5*60*1000); } #endif }
ObjectId &ObjectId::init() { static QAtomicInt inc = static_cast<unsigned>(QScopedPointer<SecureRandom>(SecureRandom::create())->nextInt64()); { unsigned t = (unsigned) ::time(0); uchar *T = (uchar *) &t; _time[0] = T[3]; // big endian order because we use memcmp() to compare OID's _time[1] = T[2]; _time[2] = T[1]; _time[3] = T[0]; } _machineAndPid = ourMachineAndPid; { const int new_inc = inc.fetchAndAddOrdered(1); uchar *T = (uchar *) &new_inc; _inc[0] = T[2]; _inc[1] = T[1]; _inc[2] = T[0]; } return *this; }
TActionWorker::TActionWorker(TEpollSocket *socket, QObject *parent) : QThread(parent), TActionContext(), httpRequest(), clientAddr(), socketId(socket->id()) { workerCounter.fetchAndAddOrdered(1); httpRequest = socket->recvBuffer().read(INT_MAX); clientAddr = socket->recvBuffer().clientAddress().toString(); }
int CRASHREPORTER_set_plugin_name(const char *plugin_name){ //fprintf(stderr,"plugin_name: -%s-\n",plugin_name); int pos = g_plugin_name_pos.fetchAndAddOrdered(1) % MAX_NUM_PLUGIN_NAMES; if (plugin_name[0]!=0) g_plugin_names[pos] = plugin_name; return pos; }
TActionThread::~TActionThread() { if (httpSocket) delete httpSocket; if (TActionContext::socketDesc > 0) TF_CLOSE(TActionContext::socketDesc); threadCounter.fetchAndAddOrdered(-1); }
QcepObject::QcepObject(QString name, QObject *parent) : QObject(parent), m_ObjectNamer(this, name)/*, m_Name(QcepSettingsSaverWPtr(), this, "name", name, "Object Name")*/ { s_ObjectAllocateCount.fetchAndAddOrdered(1); #ifndef QT_NO_DEBUG s_Allocated.insert(this); #endif }
QBluetoothTransferReplyBluez::QBluetoothTransferReplyBluez(QIODevice *input, const QBluetoothTransferRequest &request, QBluetoothTransferManager *parent) : QBluetoothTransferReply(parent), m_client(0), m_agent(0), m_clientBluez(0), m_objectPushBluez(0), m_tempfile(0), m_source(input), m_running(false), m_finished(false), m_size(0), m_error(QBluetoothTransferReply::NoError), m_errorStr(), m_transfer_path() { setRequest(request); setManager(parent); if (!input) { qCWarning(QT_BT_BLUEZ) << "Invalid input device (null)"; m_errorStr = QBluetoothTransferReply::tr("Invalid input device (null)"); m_error = QBluetoothTransferReply::FileNotFoundError; m_finished = true; return; } if (isBluez5()) { m_clientBluez = new OrgBluezObexClient1Interface(QStringLiteral("org.bluez.obex"), QStringLiteral("/org/bluez/obex"), QDBusConnection::sessionBus(), this); } else { m_client = new OrgOpenobexClientInterface(QStringLiteral("org.openobex.client"), QStringLiteral("/"), QDBusConnection::sessionBus()); m_agent_path = agentPath; m_agent_path.append(QStringLiteral("/%1%2/%3"). arg(QCoreApplication::applicationName()). arg(QCoreApplication::applicationPid()). arg(agentPathCounter.fetchAndAddOrdered(1))); m_agent = new AgentAdaptor(this); if (!QDBusConnection::sessionBus().registerObject(m_agent_path, this)) qCWarning(QT_BT_BLUEZ) << "Failed creating obex agent dbus objects"; } QMetaObject::invokeMethod(this, "start", Qt::QueuedConnection); m_running = true; }
QcepObject::~QcepObject() { #ifndef QT_NO_DEBUG QThread *currTh = QThread::currentThread(); QThread *objTh = thread(); if (objTh && currTh != objTh) { printf("Deleting object from different thread %s (%s, %s)\n", qPrintable(objectName()), qPrintable(currTh ? currTh->objectName() : "null"), qPrintable(objTh ? objTh->objectName() : "null")); } #endif s_ObjectDeleteCount.fetchAndAddOrdered(1); #ifndef QT_NO_DEBUG s_Allocated.remove(this); #endif }
unsigned Util::getRandomSeed() { /* Because std::random_device seems to be not random at all on MINGW 4.8, we use * the system time and an incrementing counter instead. */ static QAtomicInt counter; auto counterValue = unsigned(counter.fetchAndAddOrdered(1)); unsigned clockValue = quint64(QDateTime::currentMSecsSinceEpoch()) & 0xFFFFFFFFu; //qDebug() << "counterValue:" << counterValue << " clockValue:" << clockValue; auto result = counterValue ^ clockValue; qDebug() << "Util::getRandomSeed returning" << result; /* we want to avoid returning the same result twice by accident (if the clock * advance and the counter difference cancel out each other), so we sleep a * little bit */ QThread::msleep(8); return result; }
QcepImageDataBase::QcepImageDataBase(QcepSettingsSaverWPtr saver, int width, int height, int size) : QcepDataObject(saver, tr("image"), size), m_Width(saver, this, "width", width, "Image Width"), m_Height(saver, this, "height", height, "Image Height"), m_DataType(saver, this, "dataType", UndefinedData, "Data Type of Image"), m_FileBase(saver, this, "fileBase", "", "File Base of Image"), m_Title(saver, this, "title", "", "Title of Image"), m_ReadoutMode(saver, this, "readoutMode", 0, "Image Readout Mode"), m_ExposureTime(saver, this, "exposureTime", 0, "Image Exposure Time"), m_SummedExposures(saver, this, "summedExposures", 0, "Summed Exposures in Image"), m_ImageSequenceNumber(saver, this, "imageSequenceNumber", -1, "Image Sequence Number"), m_ImageNumber(saver, this, "imageNumber", 0, "Image Number"), m_PhaseNumber(saver, this, "phaseNumber", -1, "Image Phase Number"), m_NPhases(saver, this, "nPhases", -1, "Number of Image Phases"), m_DateTime(saver, this, "dateTime", QDateTime::currentDateTime(), "Image Creation Date and Time"), m_TimeStamp(saver, this, "timeStamp", secondsSinceEpoch(), "Image creation time (secs after UNIX epoch)"), m_HBinning(saver, this, "hBinning", 1, "Image Horizontal Binning Factor"), m_VBinning(saver, this, "vBinning", 1, "Image Vertical Binning Factor"), m_CameraGain(saver, this, "cameraGain", 0, "Image Detector Gain"), m_Triggered(saver, this, "triggered", 0, "Triggered Flag"), m_UserComment1(saver, this,"userComment1","", "User Comment 1"), m_UserComment2(saver, this,"userComment2","", "User Comment 2"), m_UserComment3(saver, this,"userComment3","", "User Comment 3"), m_UserComment4(saver, this,"userComment4","", "User Comment 4"), m_Normalization(saver, this, "normalization", QcepDoubleList(), "Normalization Values"), m_ExtraInputs(saver, this, "extraInputs", QcepDoubleList(), "Extra Input Values"), m_Used(saver, this, "used", true, "Image Used?"), m_ImageCounter(allocCount.fetchAndAddOrdered(1)), m_Mutex(QMutex::Recursive), m_Saver(saver) { set_Type("Image"); if (qcepDebug(DEBUG_IMAGE_CONSTRUCTORS)) { printf("QcepImageDataBase::QcepImageDataBase(%p)\n", this); } QcepAllocator::allocate(size); }
AlertSubscriptionData() : _id(QString::number(_sequence.fetchAndAddOrdered(1))), _notifyEmit(false), _notifyCancel(false), _notifyReminder(false) { }
TActionWorker::~TActionWorker() { tSystemDebug("TActionWorker::~TActionWorker"); workerCounter.fetchAndAddOrdered(-1); }
TActionThread::TActionThread(int socket) : QThread(), TActionContext(), httpSocket(0) { threadCounter.fetchAndAddOrdered(1); TActionContext::socketDesc = socket; }
void LogForwardThread::forwardMessage(LogMessage *msg) { #ifdef DUMP_PACKET QList<QByteArray>::const_iterator it = msg->begin(); int i = 0; for (; it != msg->end(); ++it, i++) { QByteArray buf = *it; cout << i << ":\t" << buf.size() << endl << "\t" << buf.toHex().constData() << endl << "\t" << buf.constData() << endl; } #endif msgsSinceHeartbeat.ref(); // First section is the client id QByteArray clientBa = msg->first(); QString clientId = QString(clientBa.toHex()); QByteArray json = msg->at(1); if (json.size() == 0) { // This is either a ping response or a first gasp logClientMapMutex.lock(); LoggerListItem *logItem = logClientMap.value(clientId, NULL); logClientMapMutex.unlock(); if (!logItem) { // Send an initial ping so the client knows we are in the house emit pingClient(clientId); } else { // cout << "pong " << clientId.toLocal8Bit().constData() << endl; loggingGetTimeStamp(&logItem->epoch, NULL); } return; } QMutexLocker lock(&logClientMapMutex); LoggerListItem *logItem = logClientMap.value(clientId, NULL); // cout << "msg " << clientId.toLocal8Bit().constData() << endl; if (logItem) { loggingGetTimeStamp(&logItem->epoch, NULL); } else { LoggingItem *item = LoggingItem::create(json); logClientCount.ref(); LOG(VB_FILE, LOG_DEBUG, QString("New Logging Client: ID: %1 (#%2)") .arg(clientId).arg(logClientCount.fetchAndAddOrdered(0))); #ifndef NOLOGSERVER // TODO FIXME This is not thread-safe! if (logClientCount.fetchAndAddOrdered(0) > 1 && m_shutdownTimer && m_shutdownTimer->isActive()) { LOG(VB_GENERAL, LOG_INFO, "Aborting shutdown timer"); m_shutdownTimer->stop(); } #endif QMutexLocker lock2(&loggerMapMutex); QMutexLocker lock3(&logRevClientMapMutex); // Need to find or create the loggers LoggerList *loggers = new LoggerList; LoggerBase *logger; // FileLogger from logFile QString logfile = item->logFile(); logfile.detach(); if (!logfile.isEmpty()) { logger = FileLogger::create(logfile, lock2.mutex()); ClientList *clients = logRevClientMap.value(logger); if (clients) clients->insert(0, clientId); if (logger && loggers) loggers->insert(0, logger); } #ifndef _WIN32 // SyslogLogger from facility int facility = item->facility(); #if CONFIG_SYSTEMD_JOURNAL if ((facility > 0) || (facility == SYSTEMD_JOURNAL_FACILITY)) { logger = SyslogLogger::create(lock2.mutex(), facility > 0); #else if (facility > 0) { logger = SyslogLogger::create(lock2.mutex()); #endif ClientList *clients = logRevClientMap.value(logger); if (clients) clients->insert(0, clientId); if (logger && loggers) loggers->insert(0, logger); } #endif // DatabaseLogger from table QString table = item->table(); if (!table.isEmpty()) { logger = DatabaseLogger::create(table, lock2.mutex()); ClientList *clients = logRevClientMap.value(logger); if (clients) clients->insert(0, clientId); if (logger && loggers) loggers->insert(0, logger); } logItem = new LoggerListItem; loggingGetTimeStamp(&logItem->epoch, NULL); logItem->list = loggers; logClientMap.insert(clientId, logItem); item->DecrRef(); } #ifndef NOLOGSERVER m_zmqPubSock->sendMessage(*msg); #else if (logItem && logItem->list && !logItem->list->isEmpty()) { LoggerList::iterator it = logItem->list->begin(); LoggingItem *item = LoggingItem::create(json); if (!item) return; for (; it != logItem->list->end(); ++it) { (*it)->logmsg(item); } item->DecrRef(); } #endif } /// \brief Stop the thread by setting the abort flag void LogForwardThread::stop(void) { m_aborted = true; }
SharedUiItemLogWrapperData(SharedUiItem wrapped, QDateTime timestamp) : _id(QString::number(_sequence.fetchAndAddOrdered(1))), _wrapped(wrapped), _timestamp(timestamp), _timestampSection(wrapped.uiSectionCount()) { }