当前位置: 首页>>代码示例>>C++>>正文


C++ QMutex::tryLock方法代码示例

本文整理汇总了C++中QMutex::tryLock方法的典型用法代码示例。如果您正苦于以下问题:C++ QMutex::tryLock方法的具体用法?C++ QMutex::tryLock怎么用?C++ QMutex::tryLock使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QMutex的用法示例。


在下文中一共展示了QMutex::tryLock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: tr

void fight::on_attack2_clicked()
{

    currentEnemy->setHitPoints(currentEnemy->getHitPoints() - currentPlayer->getPower()) ;
    ui->actionsDoneLabel->setText("You aim for the head!");
    if (currentEnemy->getHitPoints() <= 0)
    {
        QMessageBox::information( this, tr("You have won!"), tr("You're battle is done here,\nGo on your quest!") );
        accept();
        this->close();
    } else {
        QMutex mut;
        mut.tryLock(2000);
        mut.unlock();

        ui->actionsDoneLabel->setText("The enemy attacked!");

        currentPlayer->setHitPoints(currentPlayer->getHitPoints() - currentEnemy->getPower()) ;
        if (currentPlayer->getHitPoints() <= 0)
        {
            QMessageBox::information( this, tr("You have lost! D:"), tr("You're quest has ended,\nChoose a new character\n and begin your quest again") );
            accept();
            this->close();
            //NewMainWindow.close(); you cant call a function like this
        }
    }

}
开发者ID:merovigiam,项目名称:PRJ_KART,代码行数:28,代码来源:fight.cpp

示例2: checkModifiedFromOutside

void MdiChild::checkModifiedFromOutside()
{
    static QMutex mutex;
    if (!mutex.tryLock())
        return;
    QDateTime t=QFileInfo(curFile).lastModified();
    if ((curFileDate!=QDateTime())&&(QFileInfo(curFile).lastModified()!=curFileDate)) {
        if (QMessageBox::Yes==
                QMessageBox::question(this,
                                      "File modified",
                                      QString("The file %1 has been modified outside the editor. Would you like to reload it?").arg(curFile),
                                      QMessageBox::Yes|QMessageBox::No))
        {
            QFile file(curFile);
            if (!file.open(QFile::ReadOnly | QFile::Text)) {
                QMessageBox::warning(this, tr("UVE"),
                                     tr("Cannot read file %1:\n%2.")
                                     .arg(curFile)
                                     .arg(file.errorString()));
            }
           else {
                QTextStream in(&file);
                QApplication::setOverrideCursor(Qt::WaitCursor);
                setText(in.readAll());
                QApplication::restoreOverrideCursor();
                setCurrentFile(curFile);
            }
        }
        else {
            curFileDate=QFileInfo(curFile).lastModified();
        }
    }
    mutex.unlock();
}
开发者ID:manasdas17,项目名称:uve,代码行数:34,代码来源:mdichild.cpp

示例3: update_graph

void MainWindow::update_graph() {
  static QMutex mutex;
  if (!mutex.tryLock()) {
    return;
  }
  // generate some data:
  QVector<double> x(40), y(40);   // initialize with entries 0..100
  tcp_grapher g(1000, 0.4, ui->alpha_value->value(), ui->beta_value->value());
  for (int i = 0; i < 40; ++i) {
    x[i] = i;
    y[i] = g.get_next();
  }
  // create graph and assign data to it:
  ui->tcp_graph->addGraph();
  ui->tcp_graph->graph(0)->setData(x, y);
  // give the axes some labels:
  ui->tcp_graph->xAxis->setLabel("time (rtt)");
  ui->tcp_graph->xAxis->setTicks(false);
  ui->tcp_graph->yAxis->setLabel("cwnd");
  ui->tcp_graph->yAxis->setTicks(false);
  // set axes ranges, so we see all data:
  ui->tcp_graph->xAxis->setRange(0, x.size());
  ui->tcp_graph->yAxis->setRange(0, g.get_max_window());
  ui->tcp_graph->replot();
  mutex.unlock();
}
开发者ID:Gasparila,项目名称:TCPTuner,代码行数:26,代码来源:mainwindow.cpp

示例4: run

            void run()
            {
                testsTurn.release();

                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock());
                testsTurn.release();

                threadsTurn.acquire();
                QVERIFY(normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!normalMutex.tryLock(1000));
                QVERIFY(timer.elapsed() >= 1000);
                testsTurn.release();

                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(1000));
                QVERIFY(timer.elapsed() <= 1000);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                timer.start();
                QVERIFY(!normalMutex.tryLock(1000));
                QVERIFY(timer.elapsed() >= 1000);
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock(0));
                testsTurn.release();

                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(0));
                QVERIFY(timer.elapsed() < 1000);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
开发者ID:impuls14,项目名称:qt,代码行数:51,代码来源:tst_qmutex.cpp

示例5: run

 void run()
 {
     QTime t;
     t.start();
     do {
         if (mutex.tryLock())
             mutex.unlock();
     } while (t.elapsed() < one_minute/2);
 }
开发者ID:SchleunigerAG,项目名称:WinEC7_Qt5.3.1_Fixes,代码行数:9,代码来源:tst_qmutex.cpp

示例6: sync

// Wake from executive wait condition (RT-safe).
void qmidinetJackMidiThread::sync (void)
{
	if (m_mutex.tryLock()) {
		m_cond.wakeAll();
		m_mutex.unlock();
	}
#ifdef CONFIG_DEBUG
	else qDebug("qmidinetJackMidiThread[%p]::sync(): tryLock() failed.", this);
#endif
}
开发者ID:rncbc,项目名称:qmidinet,代码行数:11,代码来源:qmidinetJackMidiDevice.cpp

示例7: findTask

 ProgressTaskInfoPtr findTask(const NodePtr& node) const
 {
     assert(!tasksMutex.tryLock());
     
     for (TasksMap::const_iterator it = tasks.begin(); it!=tasks.end(); ++it) {
         if (it->first.lock() == node) {
             return it->second;
         }
     }
     return ProgressTaskInfoPtr();
 }
开发者ID:JamesLinus,项目名称:Natron,代码行数:11,代码来源:ProgressPanel.cpp

示例8: findTask

    ProgressTaskInfoPtr findTask(const TableItemConstPtr& item) const
    {
        assert( !tasksMutex.tryLock() );

        for (TasksMap::const_iterator it = tasks.begin(); it != tasks.end(); ++it) {
            if (it->second->getTableItem() == item) {
                return it->second;
            }
        }

        return ProgressTaskInfoPtr();
    }
开发者ID:ebrayton,项目名称:Natron,代码行数:12,代码来源:ProgressPanel.cpp

示例9: findNode

    NodeInfosMap::iterator findNode(const NodePtr& node)
    {
        //Private, shouldn't lock
        assert( !lock.tryLock() );

        for (NodeInfosMap::iterator it = nodeInfos.begin(); it != nodeInfos.end(); ++it) {
            if (it->first.lock() == node) {
                return it;
            }
        }

        return nodeInfos.end();
    }
开发者ID:kcotugno,项目名称:Natron,代码行数:13,代码来源:RenderStats.cpp

示例10: setDrawOffsetInternal

 void EditorWidgetBase::setDrawOffsetInternal(VSQ_NS::tick_t drawOffset) {
     static QMutex mutex;
     if (mutex.tryLock()) {
         int xScrollTo = -controllerAdapter->getXFromTick(drawOffset);
         QScrollBar *scrollBar = ui->mainContent->horizontalScrollBar();
         int maxValue = scrollBar->maximum() + scrollBar->pageStep();
         int minValue = scrollBar->minimum();
         int contentWidth = static_cast<int>(ui->mainContent->getSceneWidth());
         int value = static_cast<int>(minValue
                 + (minValue - maxValue) * static_cast<double>(xScrollTo) / contentWidth);
         if (scrollBar->value() != value) scrollBar->setValue(value);
         mutex.unlock();
     }
 }
开发者ID:cadencii,项目名称:cadencii-nt,代码行数:14,代码来源:EditorWidgetBase.cpp

示例11: lamexp_blink_window

/*
 * Make a window blink (to draw user's attention)
 */
void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
{
	static QMutex blinkMutex;

	const double maxOpac = 1.0;
	const double minOpac = 0.3;
	const double delOpac = 0.1;

	if(!blinkMutex.tryLock())
	{
		qWarning("Blinking is already in progress, skipping!");
		return;
	}
	
	try
	{
		const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
		const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
		const double opacity = poWindow->windowOpacity();
	
		for(unsigned int i = 0; i < count; i++)
		{
			for(double x = maxOpac; x >= minOpac; x -= delOpac)
			{
				poWindow->setWindowOpacity(x);
				QApplication::processEvents();
				lamexp_sleep(sleep);
			}

			for(double x = minOpac; x <= maxOpac; x += delOpac)
			{
				poWindow->setWindowOpacity(x);
				QApplication::processEvents();
				lamexp_sleep(sleep);
			}
		}

		poWindow->setWindowOpacity(opacity);
		QApplication::processEvents();
		blinkMutex.unlock();
	}
	catch(...)
	{
		blinkMutex.unlock();
		qWarning("Exception error while blinking!");
	}
}
开发者ID:BackupTheBerlios,项目名称:lamexp,代码行数:50,代码来源:Global_Utils.cpp

示例12: callSync

void TrackCollection::callSync(func lambda, QString where) {
    QMutex mutex;
    //SleepableQThread::sleep(5);
    mutex.lock();
    callAsync( [&mutex, &lambda] (void) {
        lambda();
        //SleepableQThread::sleep(5);
        mutex.unlock();
    }, where);

    while (!mutex.tryLock(5)) {
        MainExecuter::getInstance().call();
        // DBG() << "Start animation";
        // animationIsShowed = true;
    }
    mutex.unlock(); // QMutexes should be always destroyed in unlocked state.
}
开发者ID:troyane,项目名称:mixxx,代码行数:17,代码来源:trackcollection.cpp

示例13: PyBool_FromLong

static PyObject *meth_QMutex_tryLock(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QMutex *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QMutex, &sipCpp))
        {
            bool sipRes;

            Py_BEGIN_ALLOW_THREADS
            sipRes = sipCpp->tryLock();
            Py_END_ALLOW_THREADS

            return PyBool_FromLong(sipRes);
        }
    }
开发者ID:annelida,项目名称:stuff,代码行数:18,代码来源:sipQtCoreQMutex.cpp

示例14: paint

void cCustomTitleModelItem::paint(QPainter *painter,const QStyleOptionViewItem &option,const QModelIndex &index) const {
    if (!CustomTitleModelTableLockPaint.tryLock()) return;
    if ((!Table->ApplicationConfig)||(Table->InModifTable)) return;

    int             CurIndex=index.row()*Table->columnCount()+index.column();
    QModelIndexList SelList =Table->selectionModel()->selectedIndexes();
    int             CurSelIndex=SelList.count()>0?SelList[0].row()*Table->columnCount()+SelList[0].column():-1;

    if ((CurIndex==CurSelIndex)&&(CurIndex<Table->ModelTable->List.count())) painter->fillRect(option.rect,Qt::blue); else painter->fillRect(option.rect,Qt::white);

    if ((CurIndex>=0)&&(CurIndex<Table->ModelTable->List.count())) {

        painter->drawImage(option.rect.left()+10,option.rect.top()+10,
                           Table->ModelTable->List[CurIndex]->PrepareImage((Table->TimerPosition % Table->ModelTable->List[CurIndex]->Duration),NULL,Table->CurrentSlide));

        QString ModelDuration=QTime(0,0,0,0).addMSecs(Table->ModelTable->List[CurIndex]->Duration).toString("mm:ss.zzz");
        int    FontFactor=((Table->ApplicationConfig->TimelineHeight-TIMELINEMINHEIGH)/20)*10;
        QFont  font= QApplication::font();
        QPen   Pen;

        painter->setFont(font);
        #ifdef Q_OS_WIN
        font.setPointSizeF(double(110+FontFactor)/double(painter->fontMetrics().boundingRect("0").height()));                  // Scale font
        #else
        font.setPointSizeF((double(140+FontFactor)/double(painter->fontMetrics().boundingRect("0").height()))*ScreenFontAdjust);// Scale font
        #endif
        painter->setFont(font);

        Pen.setWidth(1);
        Pen.setStyle(Qt::SolidLine);
        Pen.setColor(Qt::black);
        painter->setPen(Pen);
        painter->drawText(QRect(option.rect.left()+1,option.rect.top()+1,option.rect.width()-1,option.rect.height()-1),ModelDuration,Qt::AlignCenter|Qt::AlignBottom);
        Pen.setColor(Qt::white);
        painter->setPen(Pen);
        painter->drawText(QRect(option.rect.left(),option.rect.top(),option.rect.width()-1,option.rect.height()-1),ModelDuration,Qt::AlignCenter|Qt::AlignBottom);
    }
    CustomTitleModelTableLockPaint.unlock();
}
开发者ID:JonasCz,项目名称:ffdiaporama-1604-builds,代码行数:39,代码来源:cCustomTitleModelTable.cpp

示例15: run

void SyncContactsThread::run()
{
    m_bStop = false;

    QMutex *mutex = &(g_pContactManager->m_LoadContactsMutex);

    if (mutex->tryLock(5000)==false)
    { // wait 5 seconds max.
        emit loadingContactsFinished(false, "Mutex lock failed.");
        return;
    }

    {
        // we remove connection at the end, so finish with QSqlDatabase object in this scope
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", SQLITE_DB_CONNECTION_NAME);
        db.setDatabaseName(DBPath);
        db.open();
    }

    QString resultErrorMessage;
    bool bContactsLoadedSuccessfully = true;

    if (global::IsOutlookInstalled()) {
        bContactsLoadedSuccessfully = false;

        QString db_path= g_pContactManager->getDBPath();
        QString log_path = g_AppSettingsFolderPath + "/outcall.log";

        //if outlook x64
        if (true/*IsOutlook64bit()*/) // always use helper app to avoid potential crashing in outcall
        {
            bool b64 = global::IsOutlook64bit();
            QString helper_path;
            if (b64)
                helper_path = g_AppDirPath + "/Outlook/x64/outlook_helper_x64.exe";
            else
                helper_path = g_AppDirPath + "/Outlook/outlook_helper.exe";

            QStringList arguments;
            QString exchange = "true";
            arguments << QString("LoadContacts").toLatin1().data() << db_path.toLatin1().data() << log_path.toLatin1().data() << exchange;

            //HelperProcess outlookHelperProcess(helper_path, arguments);
            QProcess outlookHelperProcess;
            if (b64)
                outlookHelperProcess.setWorkingDirectory(g_AppDirPath + "/Outlook/x64");
            else
                outlookHelperProcess.setWorkingDirectory(g_AppDirPath + "/Outlook");

            outlookHelperProcess.start(helper_path, arguments);
            if (!outlookHelperProcess.waitForStarted(10000)) {
                if (b64)
                    resultErrorMessage = "Outlook helper x64 could not be started.";
                else
                    resultErrorMessage = "Outlook helper could not be started.";
            } else {
                while (!m_bStop) {
                    if (outlookHelperProcess.waitForFinished(1000))
                        break;
                }
                if (m_bStop) {
                    outlookHelperProcess.kill();
                    resultErrorMessage = "Cancelled";
                } else {
                    resultErrorMessage = QString(outlookHelperProcess.readAllStandardOutput());

                    if (resultErrorMessage=="_ok_") {
                        bContactsLoadedSuccessfully = true;
                        resultErrorMessage = "";
                    }
                    else if (resultErrorMessage.isEmpty()) {
                        resultErrorMessage = tr("Unknown error. Check log files for more information.");
                    }

                    /*if (resultErrorMessage.isEmpty())
                        bContactsLoadedSuccessfully = true;*/
                }
            }
        }
    }

    QSqlDatabase::removeDatabase(SQLITE_DB_CONNECTION_NAME); // free resources
    mutex->unlock();

    emit loadingContactsFinished(bContactsLoadedSuccessfully, resultErrorMessage);
}
开发者ID:bicomsystems,项目名称:outcall2,代码行数:86,代码来源:SyncContactsThread.cpp


注:本文中的QMutex::tryLock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。