示例#1
0
void SndThr::run()
{
    while (!pleaseStop) {
        if (RTOS::waitReadFifo(sndShm->fifo_in[0], 200)) {
            SndFifoNotify_t dummy;
            if (RTOS::readFifo(sndShm->fifo_in[0], &dummy, sizeof(dummy), false) == sizeof(dummy)) {
                bool do_reply = false;
                switch(sndShm->msg[0].id) {
                case GETLASTEVENT:
                    sndShm->msg[0].u.last_event = app->lastSndEvt;
                    do_reply = true;
                    break;
                case FORCEEVENT: {
                    int trig = app->lastSndEvt = sndShm->msg[0].u.forced_event;
                    Debug() << "Got sound trigger " << trig << " in EmulApp manual trigger thread.";
                    trigDone = false;
                    QCoreApplication::postEvent(app, new SoundTrigEvent(trig, this));                    
                    mut.lock();
                    if (!trigDone) {
                        cond.wait(&mut); // wait forever for the trigdone!
                    }
                    mut.unlock();
                    do_reply = true;
                }
                    break;
                case SOUND: { // notified of a new sound.. note the sound now lives on the filesystem
                    unsigned id = sndShm->msg[0].u.sound.id;
                    QString fname(sndShm->msg[0].u.sound.databuf);
                    bool islooped = sndShm->msg[0].u.sound.is_looped;
                    Debug() << "Got new sound " << id << ": `" << fname << "' in EmulApp SndThr.";
                    sndDone = false;
                    QCoreApplication::postEvent(app, new SoundEvent(id, fname, islooped, this));                    
                    mut2.lock();
                    if (!sndDone) {
                        cond2.wait(&mut2); // wait forever for the trigdone!
                    }
                    mut2.unlock();
                    do_reply = true;                    
                }
                    break;
                }
                if (do_reply) {
                    dummy = 1;                    
                    RTOS::writeFifo(sndShm->fifo_out[0], &dummy, sizeof(dummy), true);
                }
            }
        }
    }
}
示例#2
0
//"Run" part of the process thread.
void ProcessThread::run()
{
	VideoCapture cap(0);
	if(!cap.isOpened())
	{
		qDebug () << "Video capture (cap) was unable to start... ";
		return;
	}
	frame_cnt=0;
	Mat matImage;
	while(!(this->isStopped))
	{
		frame_cnt++;
		cap >> matImage;
		cv::resize (matImage, matImage, Size(800, 600));
		//resize(matImage, image, Size(800,600));

		mutex.lock();
		Mat matimg = mode->process(matImage);
		QImage qimg((uchar *)matimg.data, matimg.cols, matimg.rows, QImage::Format_RGB888);
		QLabel *label = mode->getProperLabel();
		mutex.unlock();

		QWaitCondition cond;
		QMutex drawMutex;
		drawMutex.lock();
		emit drawImage (&qimg, &cond, &drawMutex, label);
		cond.wait (&drawMutex);
		drawMutex.unlock();
	}
};
void QcApplication::postSyncEvent( QcSyncEvent *e, EventHandlerFn handler )
{
  _mutex.lock();
  if( !_instance ) {
    _mutex.unlock();
    return;
  }

  if( QThread::currentThread() == _instance->thread() ) {
    (*handler)(e);
    delete(e);
  }
  else {
    QMutex mutex;
    QWaitCondition cond;

    e->_handler = handler;
    e->_cond = &cond;
    e->_mutex = &mutex;

    mutex.lock();
    postEvent( _instance, e );
    cond.wait( &mutex );
    mutex.unlock();
  }

  _mutex.unlock();
}
void QcApplication::postSyncEvent( QcSyncEvent *e, QObject *rcv )
{
  _mutex.lock();
  if( !_instance ) {
    _mutex.unlock();
    return;
  }

  if( QThread::currentThread() == rcv->thread() ) {
    sendEvent( rcv, e );
    delete e;
  }
  else {
    QMutex mutex;
    QWaitCondition cond;

    e->_cond = &cond;
    e->_mutex = &mutex;

    mutex.lock();
    postEvent( rcv, e );
    cond.wait( &mutex );
    mutex.unlock();
  }

  _mutex.unlock();
}
示例#5
0
screengrab::screengrab()
{        
    // load configuration
    conf = Config::instance();
    conf->loadSettings();

    pixelMap = new QPixmap;
    scrNum = 0;

    // delay on 250 msec
    QMutex mutex;
    mutex.lock();
    QWaitCondition pause;
    pause.wait(&mutex, 250);

    // get screen
    screenShot();

    // auto saving first screenshot
    if (conf->getAutoSave() == true)
    {
        QString format = conf->getSaveFormat();
        QString filePath = getSaveFilePath(format);
        writeScreen(filePath, format);
    }
}
bool
GenericSchedulerThreadPrivate::waitForThreadsToQuit_internal(bool allowBlockingForMainThread)
{
    if ( !_p->isRunning() ) {
        return false;
    }

    {
        QMutexLocker k(&threadStateMutex);
        if (threadState == GenericSchedulerThread::eThreadStateStopped) {
            return false;
        }
    }

    // This function may NOT be called on the main-thread, because we may deadlock if executeOnMainThread is called OR block the UI.
    if ( !allowBlockingForMainThread && ( QThread::currentThread() == qApp->thread() ) ) {
        return false;
    }

    {
        QMutexLocker k(&mustQuitMutex);
        while (mustQuit) {
            mustQuitCond.wait(&mustQuitMutex);
        }
    }

    // call pthread_join() to ensure the thread has stopped, this should be instantaneous anyway since we ensured we returned from the run() function already
    _p->wait();

    _p->onWaitForThreadToQuit();

    return true;
}
 void run()
 {
     mutex->lock();
     started.wakeOne();
     cond->wait(mutex);
     mutex->unlock();
 }
示例#8
0
 virtual void run()
 {
     m_bRunning=true;
     while(true)
     {
         m_pDataReady->wait();
         char ch;
         while (true)
         {
             if (m_bQuitRequest)
             {
                 m_bQuitRequest=false;
                 m_bRunning=false;
                 return;
             }
             m_pBufferMutex->lock();
             if (m_iIdx<(int)m_pBuffer->size())
             {
                 ch=m_pBuffer->at((uint)m_iIdx);
                 m_iIdx++;
                 m_pPort->putch(ch);
                 m_pBufferMutex->unlock();
                 if(m_iDelay>0)usleep((unsigned long)m_iDelay);
             }
             else
                 break;
         };
         m_pBuffer->resize(0);
         m_iIdx=0;
         m_pBufferMutex->unlock();
     };
 };
 void run()
 {
     readWriteLock->lockForRead();
     started.wakeOne();
     cond->wait(readWriteLock);
     readWriteLock->unlock();
 }
 void run()
 {
     mutex.lock();
     cond.wakeOne();
     cond.wait(&mutex);
     mutex.unlock();
 }
bool
GenericSchedulerThreadPrivate::waitForAbortToComplete_internal(bool allowBlockingForMainThread)
{
    if ( !_p->isRunning() ) {
        return true;
    }

    GenericSchedulerThread::ThreadStateEnum state;
    {
        QMutexLocker k(&threadStateMutex);
        state = threadState;
    }
    if ( (state == GenericSchedulerThread::eThreadStateAborted) || GenericSchedulerThread::eThreadStateIdle ) {
        return false;
    }

    // This function may NOT be called on the main-thread, because we may deadlock if executeOnMainThread is called OR block the UI.
    if ( !allowBlockingForMainThread && ( QThread::currentThread() == qApp->thread() ) ) {
        return false;
    }


    {
        // Flag that we are going to be waiting on the main-thread so that the render thread does not attempt to execute something on the main-thread
        QMutexLocker k(&abortRequestedMutex);

        while (abortRequested > 0) {
            abortRequestedCond.wait(&abortRequestedMutex);
        }
    }
    _p->onWaitForAbortCompleted();

    return true;
}
示例#12
0
void Producer1::run()
{
    qDebug() << "thread " << QThread::currentThread()->objectName() << " begin running";

  //  g_mutex.lock();

    for(int i = 1; i < 20000;i++)
    {
        for(int j = 0; j < 30000; j++)
            int r = i+j;

        if(i%10000 == 0)
            qDebug() << "Producer " << QThread::currentThread()->objectName() << " is running" << i;
    }


 //   g_mutex.unlock();

    g_mutex.lock();
    qDebug() << "thread " << QThread::currentThread()->objectName() << " before wait";
    g_con.wait(&g_mutex);
    qDebug() << "thread " << QThread::currentThread()->objectName() << " after wait";
    g_mutex.unlock();


}
示例#13
0
CodaDevicePtr SymbianDeviceManager::getCodaDevice(const QString &port)
{
    ensureInitialized();
    QMutexLocker lock(&d->m_devicesLock);
    const int idx = findByPortName(port);
    if (idx == -1) {
        qWarning("Attempt to acquire device '%s' that does not exist.", qPrintable(port));
        if (debug)
            qDebug() << *this;
        return CodaDevicePtr();
    }
    SymbianDevice& device = d->m_devices[idx];
    CodaDevicePtr& devicePtr = device.m_data->codaDevice;
    if (devicePtr.isNull() || !devicePtr->device()->isOpen()) {
        // Check we instanciate in the correct thread - we can't afford to create the CodaDevice (and more specifically, open the VirtualSerialDevice) in a thread that isn't guaranteed to be long-lived.
        // Therefore, if we're not in SymbianDeviceManager's thread, rejig things so it's opened in the main thread
        if (QThread::currentThread() != thread()) {
            // SymbianDeviceManager is owned by the main thread
            d->m_codaPortWaitMutex.lock();
            QWaitCondition waiter;
            QCoreApplication::postEvent(this, new QConstructCodaPortEvent((QEvent::Type)d->m_constructCodaPortEventType, port, &devicePtr, &waiter));
            waiter.wait(&d->m_codaPortWaitMutex);
            // When the wait returns (due to the wakeAll in SymbianDeviceManager::customEvent), the CodaDevice will be fully set up
            d->m_codaPortWaitMutex.unlock();
        } else {
            // We're in the main thread, just set it up directly
            constructCodaPort(devicePtr, port);
        }
    // We still carry on in the case we failed to open so the client can access the IODevice's errorString()
    }
    if (devicePtr->device()->isOpen())
        device.m_data->deviceAcquired++;
    return devicePtr;
}
示例#14
0
 /// sleep (?)
 void msleep ( unsigned long millisecs ) {
     QMutex mutex;
     QWaitCondition waitCondition;
     mutex.lock();
     waitCondition.wait ( &mutex, millisecs );
     mutex.unlock();
 }
 void run()
 {
     readWriteLock.lockForWrite();
     cond.wakeOne();
     cond.wait(&readWriteLock);
     readWriteLock.unlock();
 }
示例#16
0
    static bool PreLoad(const QString &cacheKey, const MythUIImage *uitype)
    {
        m_loadingImagesLock.lock();

        // Check to see if the image is being loaded by us in another thread
        if ((m_loadingImages.contains(cacheKey)) &&
            (m_loadingImages[cacheKey] == uitype))
        {
            LOG(VB_GUI | VB_FILE, LOG_DEBUG,
                QString("ImageLoader::PreLoad(%1), this "
                        "file is already being loaded by this same MythUIImage "
                        "in another thread.").arg(cacheKey));
            m_loadingImagesLock.unlock();
            return false;
        }

        // Check to see if the exact same image is being loaded anywhere else
        while (m_loadingImages.contains(cacheKey))
            m_loadingImagesCond.wait(&m_loadingImagesLock);

        m_loadingImages[cacheKey] = uitype;
        m_loadingImagesLock.unlock();

        return true;
    }
示例#17
0
void TestInvocationPlugin::doOperation(int sleepInterval, int count)
{
	for (int i = 0; i < count; ++i) {
		QWaitCondition sleep;
		sleep.wait(new QMutex(), sleepInterval);
	}
}
void
HwComposerBackend_v10::swap(EGLNativeDisplayType display, EGLSurface surface)
{
    HWC_PLUGIN_ASSERT_ZERO(!(hwc_list->retireFenceFd == -1));

    // Wait for vsync before posting new frame
    // or force swap if exceeding the vsync timeframe
    vsync_mutex.lock();
    vsync_cond.wait(&vsync_mutex, 1000/vsyncFPS);
    vsync_mutex.unlock();

    hwc_list->dpy = EGL_NO_DISPLAY;
    hwc_list->sur = EGL_NO_SURFACE;
    HWC_PLUGIN_ASSERT_ZERO(hwc_device->prepare(hwc_device, hwc_numDisplays, hwc_mList));

    // (dpy, sur) is the target of SurfaceFlinger's OpenGL ES composition for
    // HWC_DEVICE_VERSION_1_0. They aren't relevant to prepare. The set call
    // should commit this surface atomically to the display along with any
    // overlay layers.
    hwc_list->dpy = eglGetCurrentDisplay();
    hwc_list->sur = eglGetCurrentSurface(EGL_DRAW);
    dump_display_contents(hwc_list);
    HWC_PLUGIN_ASSERT_ZERO(hwc_device->set(hwc_device, hwc_numDisplays, hwc_mList));

    if (hwc_list->retireFenceFd != -1) {
        sync_wait(hwc_list->retireFenceFd, -1);
        close(hwc_list->retireFenceFd);
        hwc_list->retireFenceFd = -1;
    }
}
示例#19
0
OSMAND_CORE_API bool OSMAND_CORE_CALL OsmAnd::InitializeCore(const std::shared_ptr<const ICoreResourcesProvider>& coreResourcesProvider)
{
    if (!coreResourcesProvider)
    {
        std::cerr << "OsmAnd core requires non-null core resources provider!" << std::endl;
        return false;
    }
    
    gCoreResourcesProvider = coreResourcesProvider;

    Logger::get()->addLogSink(std::shared_ptr<ILogSink>(new DefaultLogSink()));

    InflateExplicitReferences();

    if (!QCoreApplication::instance())
    {
        LogPrintf(LogSeverityLevel::Info,
            "OsmAnd Core is initialized standalone, so going to create 'application' thread");
        _qCoreApplicationThread.reset(new QCoreApplicationThread());
        gMainThread = _qCoreApplicationThread.get();
        _qCoreApplicationThread->start();

        // Wait until global initialization will pass in that thread
        {
            QMutexLocker scopeLock(&_qCoreApplicationThreadMutex);
            while (!_qCoreApplicationThread->wasInitialized)
                REPEAT_UNTIL(_qCoreApplicationThreadWaitCondition.wait(&_qCoreApplicationThreadMutex));
        }
    }
    else
    {
        LogPrintf(LogSeverityLevel::Info,
            "OsmAnd Core is initialized inside a Qt application, so assuming that got called from application thread");
        gMainThread = QThread::currentThread();
        initializeInAppThread();
    }

    // GDAL
    GDALAllRegister();

    // SKIA
    if (!SKIA::initialize())
        return false;

    // ICU
    if (!ICU::initialize())
        return false;

    // Qt
    (void)QLocale::system(); // This will initialize system locale, since it fails to initialize concurrently

    // Text rasterizer
    TextRasterizer_initializeGlobalInstance();

    // MapSymbol intersection classes registry
    MapSymbolIntersectionClassesRegistry_initializeGlobalInstance();

    return true;
}
示例#20
0
int main(int argc, char *argv[])
{

#ifndef QT_DEBUG
    QString fileName = FilePirate::StoragePath + "captains-log.log";
    QFile *log = new QFile(fileName);
    if (log->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        out = new QTextStream(log);
        qInstallMsgHandler(logOutput);
    } else {
        qDebug() << "Error opening log file '" << fileName << "'. All debug output redirected to console.";
    }
#endif


    SingleApplication a(argc, argv, "9578A25E-F82A-4558-842C-1DE074F3C232");

    if (a.alreadyExists()) {
        qDebug() << "FilePirate is already running.";
        a.sendMessage("fg");
        return 0;
    }

    QPixmap pixmap(":/images/splash.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();
    a.processEvents();
    splash->showMessage("Loading...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    qDebug() << "Registering URL handler...";
    QDesktopServices::setUrlHandler("pirate",&FilePirate::Application(),"handleUrl");
    a.processEvents();
    // Force the user to see the splash screen for at least some time
    QMutex dummy;
    dummy.lock();
    QWaitCondition wait;
    wait.wait(&dummy, 750);
    dummy.unlock();
    // And move on to the rest of loading
    splash->showMessage("Loading settings...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    // load the settings here
    FilePirate::Application().settingsLoaded = FilePirate::Application().loadSettings();
    splash->showMessage("Loading local filelist...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    FilePirate::Application().fileMon->fullRefreshFileList();

    // bring up the filelist - this is a good time to start up the settings dialog
    // if the user hasn't done so yet...
    splash->showMessage("Finishing up...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    FilePirate::Application().moveHelpersToThreads();

    MainWindow w;
    w.show();
    splash->finish(&w);

    a.connect(&a, SIGNAL(messageAvailable(QStringList)), &w, SLOT(secondInstanceMessages(QStringList)));

    delete splash;

    return a.exec();
}
示例#21
0
文件: util.cpp 项目: panek50/agros2d
void msleep(unsigned long msecs)
{
    QWaitCondition w;
    QMutex sleepMutex;
    sleepMutex.lock();
    w.wait(&sleepMutex, msecs);
    sleepMutex.unlock();
}
    void run()
    {
        pointers.setLocalData(new Pointer);

        QMutexLocker locker(&mutex);
        cond.wakeOne();
        cond.wait(&mutex);
    }
示例#23
0
void Core::sleep(int msec)
{
    QMutex mutex;
    mutex.lock();
    QWaitCondition pause;
    pause.wait(&mutex, msec); // def 240
    mutex.unlock();
}
示例#24
0
void logServerWait(void)
{
    // cerr << "waiting" << endl;
    QMutexLocker locker(&logThreadStartedMutex);
    while (!logThreadStarted.wait(locker.mutex(), 100) && logThreadStarting);
    locker.unlock();
    // cerr << "done waiting" << endl;
}
示例#25
0
void Wait(long int time)
{
	QMutex dummy;
	dummy.lock();
	QWaitCondition waitCondition;
	waitCondition.wait(&dummy, time);
	dummy.unlock();
}
示例#26
0
void MainWindow::msleep(unsigned long msecs){
    QMutex mutex;
    mutex.lock();

    QWaitCondition waitCondition;
    waitCondition.wait(&mutex, msecs);

    mutex.unlock();
}
示例#27
0
void wl_input_wait(struct wl_input_event *ev, int sleep)
{
	WikiDisplay *display = window->display;
	QWaitCondition *w = display->waitCondition;
	QMutex mutex;

	ev->type = -1;

	do {
		mutex.lock();
		if (sleep && display->keyEventQueue->isEmpty() && display->mouseEventQueue->isEmpty()) {
			w->wait(&mutex);
		}

		if (!display->keyEventQueue->isEmpty()) {
			display->keyQueueMutex->lock();
			QKeyEvent keyEvent = display->keyEventQueue->dequeue();
			display->keyQueueMutex->unlock();
			ev->type = WL_INPUT_EV_TYPE_KEYBOARD;
			/* determine key type */
			if (keyEvent.key() == Qt::Key_Down) {
				ev->key_event.keycode = WL_INPUT_KEY_CURSOR_DOWN;
				ev->type = WL_INPUT_EV_TYPE_CURSOR;
			} else if (keyEvent.key() == Qt::Key_Up) {
				ev->key_event.keycode = WL_INPUT_KEY_CURSOR_UP;
				ev->type = WL_INPUT_EV_TYPE_CURSOR;
			} else if (keyEvent.text().length() > 0) {
				ev->key_event.keycode = keyEvent.text().at(0).unicode();
			} else {
				ev->key_event.keycode = keyEvent.key();
			}

			switch (keyEvent.type()) {
			case QEvent::KeyPress:
				ev->key_event.value = 1;
				break;
			case QEvent::KeyRelease:
				ev->key_event.value = 0;
				break;
			default:
				break;
			}
		}

		if (!display->mouseEventQueue->isEmpty()) {
			display->mouseQueueMutex->lock();
			QMouseEvent mouseEvent = display->mouseEventQueue->dequeue();
			display->mouseQueueMutex->unlock();
			ev->type = WL_INPUT_EV_TYPE_TOUCH;
			ev->touch_event.x = mouseEvent.x();
			ev->touch_event.y = mouseEvent.y();
			ev->touch_event.value = (mouseEvent.type() == QEvent::MouseButtonPress) ? 1 : 0;
		}

		mutex.unlock();
	} while (ev->type == -1 && sleep);
}
void ModelPropertyAnimation::trigger(QAbstractAnimation *animation, bool synchrone, DeletionContext deletionContext)
{
    /* The connexion below won't delete indefinitely looping animation.
     * To avoid memory leaks, the deletionContext paramater is introduced.
     */
    connect(animation, &QAbstractAnimation::finished, [=](){animation->deleteLater();});

    /* Considering what's stated in Qt's doc about Qt::AutoConnection behaviour
     * (see QObject::connect), we need to make sure
     *     ESPECIALLY WHEN this function is called from a thread other than the gui-thread:
     *         from an algorithm thread for instance,
     * that the animation passed as parameter leaves in the gui-thread,
     * so that it can perform flawlessly.
     *
     * Indeed, IN THAT CASE, performing a direct call to QAbstractAnimation::start causes the animation
     * not to perform in the way it should. So we first move it to the gui-thread and then
     * emit a signal which finally triggers its execution.
     *
     * This isn't probably the best way to address this issue, but it works.
     */
    // connect(this, &ModelPropertyAnimation::_startIt, animation, &QAbstractAnimation::start);
    // the previous syntax doesn't work due to argument count mismatching.
    connect(this, SIGNAL(_startIt()), animation, SLOT(start()));
    animation->moveToThread(QApplication::instance()->thread());
    auto startAnimation = [=]() { // define a function that will start the animation
        emit _startIt();
        // disconnect the signal, to make sure any further emission is ignored.
        disconnect(this, SIGNAL(_startIt()), animation, SLOT(start()));
    };

    QThread *t = nullptr;
    switch(deletionContext) {
    case None:                                               break;
    case ThisThread: t = thread();                           break;
    case GuiThread:  t = QApplication::instance()->thread(); break;
    }
    if(t) {
        connect(t, &QThread::finished, animation, &QAbstractAnimation::deleteLater);
    }

    if(!synchrone) {
        startAnimation();
    }
    else {
        QMutex mutex;
        QWaitCondition condition;
        auto connexion = connect(animation, &QAbstractAnimation::finished, [&condition](){condition.wakeAll();});

        mutex.lock();
        startAnimation();
        condition.wait(&mutex);
        mutex.unlock();

        disconnect(connexion);
    }
}
    void run() {
        readWriteLock->lockForWrite();

        ready = true;
        startup->wakeOne();

        returnValue = waitCondition->wait(readWriteLock, timeout);

        readWriteLock->unlock();
    }
    void run() {
        mutex->lock();

        ready = true;
        startup->wakeOne();

        returnValue = waitCondition->wait(mutex, timeout);

        mutex->unlock();
    }