Exemple #1
0
void WatekStatusu::odblokujSockety()
{
    mutCzytelnik.acquire();
    if (--iloscCzytlenikow == 0)
      pisanie.release();
    mutCzytelnik.release();
}
Exemple #2
0
void WatekStatusu::zablokujSockety()
{
    pisanieWTrakcie.acquire();
    czytanie.acquire();
    mutCzytelnik.acquire();
    if (++iloscCzytlenikow == 1)
      pisanie.acquire();
    mutCzytelnik.release();
    czytanie.release();
    pisanieWTrakcie.release();
}
void tst_QSemaphore::tryAcquire()
{
    QSemaphore semaphore;

    QCOMPARE(semaphore.available(), 0);

    semaphore.release();
    QCOMPARE(semaphore.available(), 1);
    QVERIFY(!semaphore.tryAcquire(2));
    QCOMPARE(semaphore.available(), 1);

    semaphore.release();
    QCOMPARE(semaphore.available(), 2);
    QVERIFY(!semaphore.tryAcquire(3));
    QCOMPARE(semaphore.available(), 2);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 12);
    QVERIFY(!semaphore.tryAcquire(100));
    QCOMPARE(semaphore.available(), 12);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 22);
    QVERIFY(!semaphore.tryAcquire(100));
    QCOMPARE(semaphore.available(), 22);

    QVERIFY(semaphore.tryAcquire());
    QCOMPARE(semaphore.available(), 21);

    QVERIFY(semaphore.tryAcquire());
    QCOMPARE(semaphore.available(), 20);

    QVERIFY(semaphore.tryAcquire(10));
    QCOMPARE(semaphore.available(), 10);

    QVERIFY(semaphore.tryAcquire(10));
    QCOMPARE(semaphore.available(), 0);

    // should not be able to acquire more
    QVERIFY(!semaphore.tryAcquire());
    QCOMPARE(semaphore.available(), 0);

    QVERIFY(!semaphore.tryAcquire());
    QCOMPARE(semaphore.available(), 0);

    QVERIFY(!semaphore.tryAcquire(10));
    QCOMPARE(semaphore.available(), 0);

    QVERIFY(!semaphore.tryAcquire(10));
    QCOMPARE(semaphore.available(), 0);
}
Exemple #4
0
void Customer::run() {
    waitChair.acquire(); // wait for a chair
    barberReady->acquire(); // wait for a barber to be ready
    l2.lock();
    int bID = buffer[out];
    out = (out + 1) % numBarbers;
    l2.unlock();
    waitChair.release(); // get up from the chair
    barberChair.acquire(); // wait for an available barber chair
    customerReady[bID].release(); // signal that customer is ready
    concurPrint(ID, bID);
    barberDone[bID].acquire(); // wait for barber to finish haircut
    barberChair.release(); // get up from barber's chair
}
void Producer::run()
{
    for (int i = 0; i < DataSize; ++i) {
        freeSpace.acquire();
        buffer[i % BufferSize] = alphabet[i % AlphabetSize];
        usedSpace.release();
    }
    for (int i = 0; i < DataSize; ++i) {
        if ((i % ProducerChunkSize) == 0)
            freeSpace.acquire(ProducerChunkSize);
        buffer[i % BufferSize] = alphabet[i % AlphabetSize];
        if ((i % ProducerChunkSize) == (ProducerChunkSize - 1))
            usedSpace.release(ProducerChunkSize);
    }
}
ThreadManager& ServerThreadManager::endSync(int jobId)
{
    QSemaphore *sem = semSync(jobId);
    if (sem)
        sem->release();
    return *this;
}
Exemple #7
0
void Barber::initClass(int numB, int numC, QSemaphore *r, QSemaphore *c, QSemaphore *d, int *b) {
    customersLeft.release(numC);
    barberReady = r;
    customerReady = c;
    barberDone = d;
    buffer = b;
    numBarbers = numB;
}
Exemple #8
0
void Customer::initClass(int numB, QSemaphore *r, QSemaphore *c, QSemaphore *d, int *b) {
    barberReady = r;
    customerReady = c;
    barberDone = d;
    buffer = b;
    numBarbers = numB;
    barberChair.release(numB);
}
            void run()
            {
                testsTurn.release();

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

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

                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!recursiveMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                QVERIFY(!recursiveMutex.tryLock(0));
                testsTurn.release();

                threadsTurn.acquire();
                timer.start();
                QVERIFY(recursiveMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() <= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(recursiveMutex.tryLock(waitTime));
                QVERIFY(lockCount.testAndSetRelaxed(1, 2));
                QVERIFY(lockCount.testAndSetRelaxed(2, 1));
                recursiveMutex.unlock();
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                recursiveMutex.unlock();
                testsTurn.release();

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

                threadsTurn.acquire();
                timer.start();
                QVERIFY(recursiveMutex.tryLock(0));
                QVERIFY(timer.elapsed() < waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(recursiveMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 2));
                QVERIFY(lockCount.testAndSetRelaxed(2, 1));
                recursiveMutex.unlock();
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                recursiveMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
void tst_QSemaphore::tryAcquireWithTimeoutStarvation()
{
    class Thread : public QThread
    {
    public:
        QSemaphore startup;
        QSemaphore *semaphore;
        int amountToConsume, timeout;

        void run()
        {
            startup.release();
            forever {
                if (!semaphore->tryAcquire(amountToConsume, timeout))
                    break;
                semaphore->release(amountToConsume);
            }
        }
Exemple #11
0
void Producer::run()
{
    for(int i=0;i<DataSize;i++)
    {
       freeBytes.acquire();
       buffer[i%BufferSize]=(i%BufferSize);
       usedBytes.release();
    }
}
 void run()
 {
     qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
     for (int i = 0; i < DataSize; ++i) {
         freeBytes.acquire();
         buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
         usedBytes.release();
     }
 }
Exemple #13
0
/**
 * \brief Thread-safe vypis o behu servru.
 * \param msg Sprava pre vypis
 * \retval void
 */
void debug(const char * msg) {
    static QSemaphore my_sem(1);

    my_sem.acquire();

    qDebug() << "[" << QThread::currentThreadId() << "]"
             <<QTime::currentTime().toString() << msg;

    my_sem.release();
}
Exemple #14
0
void Barber::run() {
    while (customersLeft.tryAcquire()) {
        l1.lock();
        buffer[in] = ID;
        in = (in + 1) % numBarbers;
        l1.unlock();
        barberReady->release(); // signal availability
        customerReady[ID].acquire(); // wait for customer to be sitted
        barberDone[ID].release(); // signal that hair is done
    }
}
Exemple #15
0
            void run()
            {
                testsTurn.release();

                threadsTurn.acquire();
                QVERIFY(!readWriteLock.tryLockForRead());
                testsTurn.release();

                threadsTurn.acquire();
                QVERIFY(readWriteLock.tryLockForRead());
                lockCount.ref();
                QVERIFY(readWriteLock.tryLockForRead());
                lockCount.ref();
                lockCount.deref();
                readWriteLock.unlock();
                lockCount.deref();
                readWriteLock.unlock();
                testsTurn.release();

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

                threadsTurn.acquire();
                timer.start();
                QVERIFY(readWriteLock.tryLockForRead(1000));
                QVERIFY(timer.elapsed() <= 1000);
                lockCount.ref();
                QVERIFY(readWriteLock.tryLockForRead(1000));
                lockCount.ref();
                lockCount.deref();
                readWriteLock.unlock();
                lockCount.deref();
                readWriteLock.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
Exemple #16
0
void TimetableGenerateMultipleForm::activityPlaced(int na)
{
	time_t finish_time;
	time(&finish_time);
	int seconds=int(finish_time-start_time);
	int hours=seconds/3600;
	seconds%=3600;
	int minutes=seconds/60;
	seconds%=60;
			
	////////2011-05-26
	int mact=maxActivitiesPlaced;
	int mseconds=genMulti.timeToHighestStage;

	QString s;

	bool zero=false;
	if(mseconds==0)
		zero=true;
	int hh=mseconds/3600;
	mseconds%=3600;
	int mm=mseconds/60;
	mseconds%=60;
	int ss=mseconds;

	QString tim;
	if(hh>0){
		tim+=" ";
		tim+=tr("%1 h", "hours").arg(hh);
	}
	if(mm>0){
		tim+=" ";
		tim+=tr("%1 m", "minutes").arg(mm);
	}
	if(ss>0 || zero){
		tim+=" ";
		tim+=tr("%1 s", "seconds").arg(ss);
	}
	tim.remove(0, 1);
	s+=QString("\n");
	s+=tr("Max placed activities: %1 (at %2)", "%1 represents the maximum number of activities placed, %2 is a time interval").arg(mact).arg(tim);
	///////
	
	textLabel->setText(tr("Current timetable: %1 out of %2 activities placed, %3h %4m %5s")
	 .arg(na)
	 .arg(gt.rules.nInternalActivities)
	 .arg(hours)
	 .arg(minutes)
	 .arg(seconds)+s);
	
	semaphorePlacedActivity.release();
}
Exemple #17
0
static void resumeQtApp(JNIEnv */*env*/, jobject /*thiz*/)
{
    m_surfaceMutex.lock();
    m_pauseApplicationMutex.lock();
    if (m_androidPlatformIntegration)
        m_androidPlatformIntegration->resumeApp();

    if (m_pauseApplication)
        m_pauseApplicationSemaphore.release();

    m_pauseApplicationMutex.unlock();
    m_surfaceMutex.unlock();
}
Exemple #18
0
static void setSurface(JNIEnv *env, jobject /*thiz*/, jobject jSurface)
{
#ifndef ANDROID_PLUGIN_OPENGL
    if (m_surface)
        env->DeleteGlobalRef(m_surface);
    m_surface = env->NewGlobalRef(jSurface);
#else
    m_surfaceMutex.lock();
    EGLNativeWindowType nativeWindow = ANativeWindow_fromSurface(env, jSurface);
    bool sameNativeWindow = (nativeWindow != 0 && nativeWindow == m_nativeWindow);

    m_nativeWindow = nativeWindow;
    if (m_waitForWindow)
        m_waitForWindowSemaphore.release();

    if (m_androidPlatformIntegration) {
        // Use the desktop size.
        // On some devices, the getters for the native window size gives wrong values
        QSize size = QAndroidPlatformIntegration::defaultDesktopSize();

        QPlatformScreen *screen = m_androidPlatformIntegration->screen();
        QRect geometry(QPoint(0, 0), size);
        if (screen) {
            QWindowSystemInterface::handleScreenAvailableGeometryChange(screen->screen(), geometry);
            QWindowSystemInterface::handleScreenGeometryChange(screen->screen(), geometry);
        }

        if (!sameNativeWindow) {
            m_surfaceMutex.unlock();
            m_androidPlatformIntegration->surfaceChanged();
        } else {
            // Resize all top level windows, since they share the same surface
            foreach (QWindow *w, QGuiApplication::topLevelWindows()) {
                QAndroidOpenGLPlatformWindow *window =
                        static_cast<QAndroidOpenGLPlatformWindow *>(w->handle());

                if (window != 0) {
                    window->lock();
                    window->scheduleResize(size);

                    QWindowSystemInterface::handleExposeEvent(window->window(),
                                                              QRegion(window->window()->geometry()));
                    window->unlock();
                }
            }

            m_surfaceMutex.unlock();
        }

    } else {
Exemple #19
0
            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();
            }
Exemple #20
0
            void run()
            {
                testsTurn.release();

                threadsTurn.acquire();
                if (readWriteLock.tryLockForWrite())
                    failureCount++;
                testsTurn.release();

                threadsTurn.acquire();
                if (!readWriteLock.tryLockForWrite())
                    failureCount++;
                if (!lockCount.testAndSetRelaxed(0, 1))
                    failureCount++;
                if (!lockCount.testAndSetRelaxed(1, 0))
                    failureCount++;
                readWriteLock.unlock();
                testsTurn.release();

                threadsTurn.acquire();
                if (readWriteLock.tryLockForWrite(1000))
                    failureCount++;
                testsTurn.release();

                threadsTurn.acquire();
                if (!readWriteLock.tryLockForWrite(1000))
                    failureCount++;
                if (!lockCount.testAndSetRelaxed(0, 1))
                    failureCount++;
                if (!lockCount.testAndSetRelaxed(1, 0))
                    failureCount++;
                readWriteLock.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
void TextProducer::run()
{
    static int index = 0;
    static QMutex indexMutex;

    for( int i=0; i<m_text.length(); ++i )
    {
        freeSpace.acquire();
        indexMutex.lock();
        buffer[ index++ % bufferSize ] = m_text[i];
        indexMutex.unlock();

        if( i == m_text.length()-1 )
            //atEnd = true;
            atEnd.acquire();

        availableData.release();
    }
}
void RadioSendThread::run()
{

    RadioServer Server;
    if (!Server.Open())
    {
        printf("Server Open failed!\r\n");
        return;
    }

    int size;
    while (true)
    {

        qDebug() << "Available: " << RadioSendRequest.available();
        RadioSendRequest.acquire();
        if (shutdownView)break;
        RadioSendMutex.lock();
        RadioCmds.set_time_stamp(0);
        size= RadioCmds.cmds_size();
        qDebug() << "size:" << size;
        qDebug() << "IsInitialized: " << RadioCmds.IsInitialized();

        if (RadioCmds.IsInitialized() && size>0 && size<10)
        {

            RadioCmds.set_time_stamp(0);
            Server.Send(RadioCmds);
            qDebug() << "sending";
        }
        else
        {
            printf("Radio Send Packet Error!\r\n");
        }

        Server.Send(RadioCmds);

        RadioCmds.clear_cmds();
        RadioSendMutex.unlock();
        RadioSendRequest.release();
    }
}
Exemple #23
0
void TimetableGenerateMultipleForm::timetableGenerated(int timetable, const QString& description, bool ok)
{
	TimetableExport::writeRandomSeed(this, timetable, false); //false represents 'before' state

	QString s=QString("");
	s+=tr("Timetable no: %1 => %2", "%1 is the number of this timetable when generating multiple timetables, %2 is its description").arg(timetable).arg(description);
	currentResultsTextEdit->appendPlainText(s);
	
	bool begin;
	if(timetable==1)
		begin=true;
	else
		begin=false;
	TimetableExport::writeReportForMultiple(this, s, begin);

	if(ok){
		//needed to get the conflicts string
		QString tmp;
		genMulti.c.fitness(gt.rules, &tmp);
	
		TimetableExport::getStudentsTimetable(genMulti.c);
		TimetableExport::getTeachersTimetable(genMulti.c);
		TimetableExport::getRoomsTimetable(genMulti.c);

		TimetableExport::writeSimulationResults(this, timetable);

		//update the string representing the conflicts
		conflictsStringTitle=tr("Soft conflicts", "Title of dialog");
		conflictsString = "";
		conflictsString+=tr("Total soft conflicts:");
		conflictsString+=" ";
		conflictsString+=CustomFETString::number(best_solution.conflictsTotal);
		conflictsString+="\n";
		conflictsString += tr("Soft conflicts listing (in decreasing order):")+"\n";

		foreach(QString t, best_solution.conflictsDescriptionList)
			conflictsString+=t+"\n";
	}

	semaphoreTimetableFinished.release();
}
void SqlwriteThread_buffer::run()
{
    QString databaseseq;

    QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL",databaseseq.setNum(m_index));
    database.setHostName(m_hostname);
    database.setDatabaseName(m_databasename);
    database.setUserName(m_usrname);
    database.setPassword(m_psword);

    if (!database.open())
    {
        database.close();
        qDebug()<<trUtf8("数据库打不开")<<endl;
        return ;
    }
    else
    {
        qDebug()<<trUtf8("线程内数据已经打开")<<endl;
    }


    /*
    QString i2c;
    QFile timelog("timelog"+i2c.setNum(m_index)+".txt");
    if (!timelog.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        qDebug()<<trUtf8("LOG日志没有打开")<<endl;
        return;
    }
    timelog.close();
    */

    QSqlQuery sqlquery(database);
    //    QTime timerecord;
    //    timerecord.start();
    qDebug()<<"sqltest thread runing...";

    mysqldata *data=g_buffer.data();
    mysqldata tempdata;
    bool flag = true;
    while(g_rIndex < DATABLOCKSIZE)
    {
        mutex.lock();
        if(usedBuffer.tryAcquire())
        {            
            flag = false;
            int index=g_rIndex;
            ++g_rIndex;
            qDebug()<<QThread::currentThreadId()<<trUtf8("线程读写第")
                    <<index<<trUtf8("块数据,now数据缓存区内存有 ")<<usedBuffer.available()+1<<" blocks!";

            mutex.unlock();     //先锁住rindex,如果能获取得到资源,就取走该资源。rndex指向该资源。
            tempdata = data[index % 10];

            //qDebug()<<"-";//
            freeBuffer.release();
        }
        else
        {
            mutex.unlock();
            continue;
        }

        int range = tempdata.datavector.size();
        for(int i=0;i <= range/SQLLINE ; ++i)		//i要改成大数,同range
        {
            QString sqlstatement = "";
            int statementnum =( (i+1)*SQLLINE > range ) ? range - i*SQLLINE: SQLLINE;
            sqlstatement="insert into InsertTest("
                    "id,"
                    "taskseq,"
                    "protocoltype ,"
                    "threadnumintask,"
                    "idinthread,"
                    "framesize,"
                    "DestMac,"
                    "SourMac,"
                    "TypeorLength,"
                    "Data,"
                    "Upperlayer) VALUES";


            for(int j=0; j < statementnum; j++)
            {
                sqlstatement += "("+tempdata.idvector.at(i*SQLLINE + j);
                sqlstatement += "," + tempdata.taskseqvector.at(i*SQLLINE + j);
                sqlstatement += ", '" + tempdata.typevector.at(i*SQLLINE + j)+"'";
                sqlstatement += "," + tempdata.threadnumvector.at(i*SQLLINE + j);
                sqlstatement += "," + tempdata.idinthreadvector.at(i*SQLLINE + j);
                sqlstatement += "," + tempdata.framesizevector.at(i*SQLLINE + j);
                sqlstatement += ", '" + tempdata.DestMacvector.at(i*SQLLINE + j)+"'";
                sqlstatement += ", '" + tempdata.SourMacvector.at(i*SQLLINE + j)+"'";
                sqlstatement += ", '" + tempdata.TypeorLengthvector.at(i*SQLLINE + j)+"'";
                sqlstatement += ", '" + tempdata.datavector.at(i*SQLLINE + j)+"'";
                sqlstatement += ", '" + tempdata.uplayervector.at(i*SQLLINE + j)+"')";
                if( j == statementnum -1) sqlstatement += ";";
                else sqlstatement += ",";
            }
            if( statementnum != 0 )
            {
                if(!sqlquery.exec(sqlstatement))
                {
                    qDebug()<<"block--"<<i<<"\t\n"<<sqlquery.lastError().databaseText();
                    qDebug()<<trUtf8("发生语句错误")<<sqlstatement;
                    return;
                }

            }
            else
            {
                break;
            }
        }


    }




    //    timelog.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
    //    QTextStream logout(&timelog);
    //    logout << "Insert "<<m_range<<" Lines to SQL need time : " << timerecord.elapsed() << "(ms)\n";
    //    timelog.close();


    database.close();
    qDebug()<<m_index<<"_thread run over!"<<endl;
}
Exemple #25
0
 void waitForTest()
 {
     semaphore.release();
     testSemaphore.acquire();
 }
            void run()
            {
                testsTurn.release();

                // TEST 1: thread can't acquire lock
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock());
                testsTurn.release();

                // TEST 2: thread can acquire lock
                threadsTurn.acquire();
                QVERIFY(normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 3: thread can't acquire lock, timeout = waitTime
                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                testsTurn.release();

                // TEST 4: thread can acquire lock, timeout = waitTime
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() <= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                timer.start();
                // it's non-recursive, so the following lock needs to fail
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 5: thread can't acquire lock, timeout = 0
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock(0));
                testsTurn.release();

                // TEST 6: thread can acquire lock, timeout = 0
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(0));
                QVERIFY(timer.elapsed() < waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 7 overflow: thread can acquire lock, timeout = 3000 (QTBUG-24795)
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(3000));
                QVERIFY(timer.elapsed() < 3000);
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
void tst_QMutex::tryLock()
{
    // test non-recursive mutex
    {
        class Thread : public QThread
        {
        public:
            void run()
            {
                testsTurn.release();

                // TEST 1: thread can't acquire lock
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock());
                testsTurn.release();

                // TEST 2: thread can acquire lock
                threadsTurn.acquire();
                QVERIFY(normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 3: thread can't acquire lock, timeout = waitTime
                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                testsTurn.release();

                // TEST 4: thread can acquire lock, timeout = waitTime
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() <= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                timer.start();
                // it's non-recursive, so the following lock needs to fail
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 5: thread can't acquire lock, timeout = 0
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock(0));
                testsTurn.release();

                // TEST 6: thread can acquire lock, timeout = 0
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(0));
                QVERIFY(timer.elapsed() < waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 7 overflow: thread can acquire lock, timeout = 3000 (QTBUG-24795)
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(3000));
                QVERIFY(timer.elapsed() < 3000);
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
        };

        Thread thread;
        thread.start();

        // TEST 1: thread can't acquire lock
        testsTurn.acquire();
        normalMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        threadsTurn.release();

        // TEST 2: thread can acquire lock
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        normalMutex.unlock();
        threadsTurn.release();

        // TEST 3: thread can't acquire lock, timeout = waitTime
        testsTurn.acquire();
        normalMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        threadsTurn.release();

        // TEST 4: thread can acquire lock, timeout = waitTime
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        normalMutex.unlock();
        threadsTurn.release();

        // TEST 5: thread can't acquire lock, timeout = 0
        testsTurn.acquire();
        normalMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        threadsTurn.release();

        // TEST 6: thread can acquire lock, timeout = 0
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        normalMutex.unlock();
        threadsTurn.release();

        // TEST 7: thread can acquire lock, timeout = 3000   (QTBUG-24795)
        testsTurn.acquire();
        normalMutex.lock();
        threadsTurn.release();
        QThread::msleep(100);
        normalMutex.unlock();

        // wait for thread to finish
        testsTurn.acquire();
        threadsTurn.release();
        thread.wait();
    }

    // test recursive mutex
    {
        class Thread : public QThread
        {
        public:
            void run()
            {
                testsTurn.release();

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

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

                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!recursiveMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                QVERIFY(!recursiveMutex.tryLock(0));
                testsTurn.release();

                threadsTurn.acquire();
                timer.start();
                QVERIFY(recursiveMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() <= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(recursiveMutex.tryLock(waitTime));
                QVERIFY(lockCount.testAndSetRelaxed(1, 2));
                QVERIFY(lockCount.testAndSetRelaxed(2, 1));
                recursiveMutex.unlock();
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                recursiveMutex.unlock();
                testsTurn.release();

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

                threadsTurn.acquire();
                timer.start();
                QVERIFY(recursiveMutex.tryLock(0));
                QVERIFY(timer.elapsed() < waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(recursiveMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 2));
                QVERIFY(lockCount.testAndSetRelaxed(2, 1));
                recursiveMutex.unlock();
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                recursiveMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
        };

        Thread thread;
        thread.start();

        // thread can't acquire lock
        testsTurn.acquire();
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 2));
        threadsTurn.release();

        // thread can acquire lock
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(2, 1));
        recursiveMutex.unlock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        recursiveMutex.unlock();
        threadsTurn.release();

        // thread can't acquire lock, timeout = waitTime
        testsTurn.acquire();
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 2));
        threadsTurn.release();

        // thread can acquire lock, timeout = waitTime
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(2, 1));
        recursiveMutex.unlock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        recursiveMutex.unlock();
        threadsTurn.release();

        // thread can't acquire lock, timeout = 0
        testsTurn.acquire();
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(0, 1));
        recursiveMutex.lock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 2));
        threadsTurn.release();

        // thread can acquire lock, timeout = 0
        testsTurn.acquire();
        QVERIFY(lockCount.testAndSetRelaxed(2, 1));
        recursiveMutex.unlock();
        QVERIFY(lockCount.testAndSetRelaxed(1, 0));
        recursiveMutex.unlock();
        threadsTurn.release();

        // stop thread
        testsTurn.acquire();
        threadsTurn.release();
        thread.wait();
    }
}
void tst_QSemaphore::acquire()
{
    {
        // old incrementOne() test
        QVERIFY(!semaphore);
        semaphore = new QSemaphore;
        // make some "thing" available
        semaphore->release();

        ThreadOne t1;
        ThreadOne t2;

        t1.start();
        t2.start();

        QVERIFY(t1.wait(4000));
        QVERIFY(t2.wait(4000));

        delete semaphore;
        semaphore = 0;
    }

    // old incrementN() test
    {
        QVERIFY(!semaphore);
        semaphore = new QSemaphore;
        // make 4 "things" available
        semaphore->release(4);

        ThreadN t1(2);
        ThreadN t2(3);

        t1.start();
        t2.start();

        QVERIFY(t1.wait(4000));
        QVERIFY(t2.wait(4000));

        delete semaphore;
        semaphore = 0;
    }

    QSemaphore semaphore;

    QCOMPARE(semaphore.available(), 0);
    semaphore.release();
    QCOMPARE(semaphore.available(), 1);
    semaphore.release();
    QCOMPARE(semaphore.available(), 2);
    semaphore.release(10);
    QCOMPARE(semaphore.available(), 12);
    semaphore.release(10);
    QCOMPARE(semaphore.available(), 22);

    semaphore.acquire();
    QCOMPARE(semaphore.available(), 21);
    semaphore.acquire();
    QCOMPARE(semaphore.available(), 20);
    semaphore.acquire(10);
    QCOMPARE(semaphore.available(), 10);
    semaphore.acquire(10);
    QCOMPARE(semaphore.available(), 0);
}
void tst_QSemaphore::tryAcquireWithTimeout()
{
    QFETCH(int, timeout);

    // timers are not guaranteed to be accurate down to the last millisecond,
    // so we permit the elapsed times to be up to this far from the expected value.
    int fuzz = 50;

    QSemaphore semaphore;
    QElapsedTimer time;

#define FUZZYCOMPARE(a,e) \
    do { \
        int a1 = a; \
        int e1 = e; \
        QVERIFY2(qAbs(a1-e1) < fuzz, \
            qPrintable(QString("(%1=%2) is more than %3 milliseconds different from (%4=%5)") \
                        .arg(#a).arg(a1).arg(fuzz).arg(#e).arg(e1))); \
    } while (0)

    QCOMPARE(semaphore.available(), 0);

    semaphore.release();
    QCOMPARE(semaphore.available(), 1);
    time.start();
    QVERIFY(!semaphore.tryAcquire(2, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 1);

    semaphore.release();
    QCOMPARE(semaphore.available(), 2);
    time.start();
    QVERIFY(!semaphore.tryAcquire(3, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 2);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 12);
    time.start();
    QVERIFY(!semaphore.tryAcquire(100, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 12);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 22);
    time.start();
    QVERIFY(!semaphore.tryAcquire(100, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 22);

    time.start();
    QVERIFY(semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 21);

    time.start();
    QVERIFY(semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 20);

    time.start();
    QVERIFY(semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 10);

    time.start();
    QVERIFY(semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 0);

    // should not be able to acquire more
    time.start();
    QVERIFY(!semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

#undef FUZZYCOMPARE
}
Exemple #30
0
 void run()
 {
     semaphore.release();
 }