static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id.load()) \
         metatype_id.store(qRegisterMetaType< QPair<qreal,QColor > >("QPair<qreal,QColor >")); \
     return metatype_id.load(); \
 } \
 static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id) \
         metatype_id = qRegisterMetaType< QVector<QPair<qreal,QColor> > >("QVector<QPair<qreal,QColor> >"); \
     return metatype_id; \
 } \
void tst_QThreadStorage::ensureCleanupOrder()
{
    class Thread : public QThread
    {
    public:
        QThreadStorage<First *> &first;
        QThreadStorage<Second *> &second;

        Thread(QThreadStorage<First *> &first,
               QThreadStorage<Second *> &second)
            : first(first), second(second)
        { }

        void run()
        {
            // set in reverse order, but shouldn't matter, the data
            // will be deleted in the order the thread storage objects
            // were created
            second.setLocalData(new Second);
            first.setLocalData(new First);
        }
    };

    QThreadStorage<Second *> second;
    QThreadStorage<First *> first;
    Thread thread(first, second);
    thread.start();
    thread.wait();

    QVERIFY(First::order < Second::order);
}
static int unixCheckClockType()
{
#if (_POSIX_MONOTONIC_CLOCK-0 == 0) && defined(_SC_MONOTONIC_CLOCK)
    // we need a value we can store in a clockid_t that isn't a valid clock
    // check if the valid ones are both non-negative or both non-positive
#  if CLOCK_MONOTONIC >= 0 && CLOCK_REALTIME >= 0
#    define IS_VALID_CLOCK(clock)    (clock >= 0)
#    define INVALID_CLOCK            -1
#  elif CLOCK_MONOTONIC <= 0 && CLOCK_REALTIME <= 0
#    define IS_VALID_CLOCK(clock)    (clock <= 0)
#    define INVALID_CLOCK            1
#  else
#    error "Sorry, your system has weird values for CLOCK_MONOTONIC and CLOCK_REALTIME"
#  endif

    static QBasicAtomicInt clockToUse = Q_BASIC_ATOMIC_INITIALIZER(INVALID_CLOCK);
    int clock = clockToUse.loadAcquire();
    if (Q_LIKELY(IS_VALID_CLOCK(clock)))
        return clock;

    // detect if the system supports monotonic timers
    clock = sysconf(_SC_MONOTONIC_CLOCK) > 0 ? CLOCK_MONOTONIC : CLOCK_REALTIME;
    clockToUse.storeRelease(clock);
    return clock;

#  undef INVALID_CLOCK
#  undef IS_VALID_CLOCK
#elif (_POSIX_MONOTONIC_CLOCK-0) > 0
    return CLOCK_MONOTONIC;
#else
    return CLOCK_REALTIME;
#endif
}
 static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id.load()) \
         metatype_id.store(qRegisterMetaType< QHash<int,QByteArray > >("QHash<int,QByteArray >")); \
     return metatype_id.load(); \
 } \
 static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id) \
         metatype_id = qRegisterMetaType< QMap<int,QVariant> >("QMap<int,QVariant>"); \
     return metatype_id; \
 } \
 static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id) \
         metatype_id = qRegisterMetaType< QList<QPair<QByteArray,QString> > >("QList<QPair<QByteArray,QString> >"); \
     return metatype_id; \
 } \
 static int qt_metatype_id() \
 { \
     static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
     if (!metatype_id) \
         metatype_id = qRegisterMetaType< QMultiMap<QString,QString> >("QMultiMap<QString,QString>"); \
     return metatype_id; \
 } \
// Lifted from Qt. I don't think they would mind. ;)
// Re-lift again from Qt whenever a proper replacement for pthread_once appears
static void qt_ignore_sigpipe()
{
    static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0);
    if (atom.testAndSetRelaxed(0, 1)) {
        struct sigaction noaction;
        memset(&noaction, 0, sizeof(noaction));
        noaction.sa_handler = SIG_IGN;
        sigaction(SIGPIPE, &noaction, 0);
    }
}
Exemple #10
0
    static void messageHandler(QtMsgType type, const QMessageLogContext & context, const QString &message)
    {
        static QBasicAtomicInt counter = Q_BASIC_ATOMIC_INITIALIZER(QTest::maxWarnings);

        if (QTest::TestLoggers::loggerCount() == 0) {
            // if this goes wrong, something is seriously broken.
            qInstallMessageHandler(oldMessageHandler);
            QTEST_ASSERT(QTest::TestLoggers::loggerCount() != 0);
        }

        if (handleIgnoredMessage(type, message))
            // the message is expected, so just swallow it.
            return;

        QString msg = qFormatLogMessage(type, context, message);

        if (type != QtFatalMsg) {
            if (counter.load() <= 0)
                return;

            if (!counter.deref()) {
                QTest::TestLoggers::addMessage(QAbstractTestLogger::QSystem,
                        QStringLiteral("Maximum amount of warnings exceeded. Use -maxwarnings to override."));
                return;
            }
        }

        switch (type) {
        case QtDebugMsg:
            QTest::TestLoggers::addMessage(QAbstractTestLogger::QDebug, msg);
            break;
        case QtCriticalMsg:
            QTest::TestLoggers::addMessage(QAbstractTestLogger::QSystem, msg);
            break;
        case QtWarningMsg:
            QTest::TestLoggers::addMessage(QAbstractTestLogger::QWarning, msg);
            break;
        case QtFatalMsg:
            QTest::TestLoggers::addMessage(QAbstractTestLogger::QFatal, msg);
            /* Right now, we're inside the custom message handler and we're
             * being qt_message_output in qglobal.cpp. After we return from
             * this function, it will proceed with calling exit() and abort()
             * and hence crash. Therefore, we call these logging functions such
             * that we wrap up nicely, and in particular produce well-formed XML. */
            QTestResult::addFailure("Received a fatal error.", "Unknown file", 0);
            QTestLog::leaveTestFunction();
            QTestLog::stopLogging();
            break;
        }
    }
Exemple #11
0
EGLNativeWindowType QEglFSEmulatorIntegration::createNativeWindow(QPlatformWindow *platformWindow,
                                                                  const QSize &size,
                                                                  const QSurfaceFormat &format)
{
    Q_UNUSED(size);
    Q_UNUSED(format);
    QEglFSEmulatorScreen *screen = static_cast<QEglFSEmulatorScreen *>(platformWindow->screen());
    if (screen && setDisplay) {
        // Let the emulator know which screen the window surface is attached to
        setDisplay(screen->id());
    }
    static QBasicAtomicInt uniqueWindowId = Q_BASIC_ATOMIC_INITIALIZER(0);
    return EGLNativeWindowType(qintptr(1 + uniqueWindowId.fetchAndAddRelaxed(1)));
}
Exemple #12
0
static void qt_ignore_sigpipe()
{
#ifndef Q_NO_POSIX_SIGNALS
    // Set to ignore SIGPIPE once only.
    static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0);
    if (atom.testAndSetRelaxed(0, 1)) {
        struct sigaction noaction;
        memset(&noaction, 0, sizeof(noaction));
        noaction.sa_handler = SIG_IGN;
        ::sigaction(SIGPIPE, &noaction, 0);
    }
#else
    // Posix signals are not supported by the underlying platform
    // so we don't need to ignore sigpipe signal explicitly
#endif
}
Exemple #13
0
KConfigPrivate::KConfigPrivate(KConfig::OpenFlags flags,
                               QStandardPaths::StandardLocation resourceType)
    : openFlags(flags), resourceType(resourceType), mBackend(Q_NULLPTR),
      bDynamicBackend(true),  bDirty(false), bReadDefaults(false),
      bFileImmutable(false), bForceGlobal(false), bSuppressGlobal(false),
      configState(KConfigBase::NoAccess)
{
    static QBasicAtomicInt use_etc_kderc = Q_BASIC_ATOMIC_INITIALIZER(-1);
    if (use_etc_kderc.load() < 0) {
        use_etc_kderc.store( !qEnvironmentVariableIsSet("KDE_SKIP_KDERC"));    // for unit tests
    }
    if (use_etc_kderc.load()) {

        etc_kderc =
#ifdef Q_OS_WIN
            QFile::decodeName(qgetenv("WINDIR") + "/kde5rc");
#else
            QStringLiteral("/etc/kde5rc");
#endif
        if (!QFileInfo(etc_kderc).isReadable()) {
            etc_kderc.clear();
        }
    }

//    if (!mappingsRegistered) {
//        KEntryMap tmp;
//        if (!etc_kderc.isEmpty()) {
//            QExplicitlySharedDataPointer<KConfigBackend> backend = KConfigBackend::create(etc_kderc, QLatin1String("INI"));
//            backend->parseConfig( "en_US", tmp, KConfigBackend::ParseDefaults);
//        }
//        const QString kde5rc(QDir::home().filePath(".kde5rc"));
//        if (KStandardDirs::checkAccess(kde5rc, R_OK)) {
//            QExplicitlySharedDataPointer<KConfigBackend> backend = KConfigBackend::create(kde5rc, QLatin1String("INI"));
//            backend->parseConfig( "en_US", tmp, KConfigBackend::ParseOptions());
//        }
//        KConfigBackend::registerMappings(tmp);
//        mappingsRegistered = true;
//    }

    setLocale(QLocale().name());
}
static qint64 getticks()
{
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
    clockid_t clockId;

#ifndef _POSIX_THREAD_CPUTIME
    clockId = CLOCK_REALTIME;
#elif (_POSIX_THREAD_CPUTIME-0 <= 0)
    // if we don't have CLOCK_THREAD_CPUTIME_ID, we have to just use elapsed realtime instead
    clockId = CLOCK_REALTIME;

#  if (_POSIX_THREAD_CPUTIME-0 == 0)
    // detect availablility of CLOCK_THREAD_CPUTIME_ID
    static QBasicAtomicInt sUseThreadCpuTime = Q_BASIC_ATOMIC_INITIALIZER(-2);
    int useThreadCpuTime = sUseThreadCpuTime.load();
    if (useThreadCpuTime == -2) {
        // sysconf() will return either -1L or _POSIX_VERSION
        // (don't care about sysconf's exact return value)
        useThreadCpuTime = sysconf(_SC_THREAD_CPUTIME) == -1L ? -1 : 0 ;
        sUseThreadCpuTime.store(useThreadCpuTime); // might happen multiple times, but doesn't matter
    }
    if (useThreadCpuTime != -1)
        clockId = CLOCK_THREAD_CPUTIME_ID;
#  endif
#else
    clockId = CLOCK_THREAD_CPUTIME_ID;
#endif

    struct timespec ts;
    if (clock_gettime(clockId, &ts) == -1)
        return 0;
    return (ts.tv_sec * 1000000000) + ts.tv_nsec;
#else

    // no clock_gettime(), fall back to wall time
    struct timeval tv;
    gettimeofday(&tv, 0);
    return (tv.tv_sec * 1000000) + tv.tv_usec;
#endif
}
void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress)
{
    Q_Q(QVariantAnimation);

    const qreal startProgress = currentInterval.start.first;
    const qreal endProgress = currentInterval.end.first;
    const qreal localProgress = (progress - startProgress) / (endProgress - startProgress);

    QVariant ret = q->interpolated(currentInterval.start.second,
                                   currentInterval.end.second,
                                   localProgress);
    qSwap(currentValue, ret);
    q->updateCurrentValue(currentValue);
    static QBasicAtomicInt changedSignalIndex = Q_BASIC_ATOMIC_INITIALIZER(0);
    if (!changedSignalIndex) {
        //we keep the mask so that we emit valueChanged only when needed (for performance reasons)
        changedSignalIndex.testAndSetRelaxed(0, signalIndex("valueChanged(QVariant)"));
    }
    if (isSignalConnected(changedSignalIndex) && currentValue != ret) {
        //the value has changed
        emit q->valueChanged(currentValue);
    }
}
Exemple #16
0
QT_BEGIN_NAMESPACE

static void resolveLibrary()
{
    static QBasicAtomicInt triedResolve = Q_BASIC_ATOMIC_INITIALIZER(false);

    if (!triedResolve.loadAcquire()) {
#ifndef QT_NO_THREAD
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_WlanOpenHandle));
#endif

        if (!triedResolve.load()) {
            local_WlanOpenHandle = (WlanOpenHandleProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanOpenHandle");
            local_WlanRegisterNotification = (WlanRegisterNotificationProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanRegisterNotification");
            local_WlanEnumInterfaces = (WlanEnumInterfacesProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanEnumInterfaces");
            local_WlanGetAvailableNetworkList = (WlanGetAvailableNetworkListProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanGetAvailableNetworkList");
            local_WlanQueryInterface = (WlanQueryInterfaceProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanQueryInterface");
            local_WlanConnect = (WlanConnectProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanConnect");
            local_WlanDisconnect = (WlanDisconnectProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanDisconnect");
            local_WlanScan = (WlanScanProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanScan");
            local_WlanFreeMemory = (WlanFreeMemoryProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanFreeMemory");
            local_WlanCloseHandle = (WlanCloseHandleProto)
                QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanCloseHandle");

            triedResolve.storeRelease(true);
        }
    }
}
    QNetworkAccessBackendFactoryData() : mutex(QMutex::Recursive)
    {
        valid.ref();
    }
    ~QNetworkAccessBackendFactoryData()
    {
        QMutexLocker locker(&mutex); // why do we need to lock?
        valid.deref();
    }

    QMutex mutex;
    //this is used to avoid (re)constructing factory data from destructors of other global classes
    static QBasicAtomicInt valid;
};
Q_GLOBAL_STATIC(QNetworkAccessBackendFactoryData, factoryData)
QBasicAtomicInt QNetworkAccessBackendFactoryData::valid = Q_BASIC_ATOMIC_INITIALIZER(0);

QNetworkAccessBackendFactory::QNetworkAccessBackendFactory()
{
    QMutexLocker locker(&factoryData()->mutex);
    factoryData()->append(this);
}

QNetworkAccessBackendFactory::~QNetworkAccessBackendFactory()
{
    if (QNetworkAccessBackendFactoryData::valid.load()) {
        QMutexLocker locker(&factoryData()->mutex);
        factoryData()->removeAll(this);
    }
}
 * return -1 / EWOULDBLOCK, in which case we have to start over. And even if we
 * are woken up directly by a FUTEX_WAKE, we need to acquire the mutex, so we
 * start over again.
 *
 * UNLOCKING (non-recursive):
 *
 * To unlock, we need to set a value of 0x0 to indicate it's unlocked. The
 * first attempt is a testAndSetRelease operation from 0x1 to 0x0. If that
 * succeeds, we're done.
 *
 * If it fails, unlockInternal() is called. The only possibility is that the
 * mutex value was 0x3, which indicates some other thread is waiting or was
 * waiting in the past. We then set the mutex to 0x0 and perform a FUTEX_WAKE.
 */

static QBasicAtomicInt futexFlagSupport = Q_BASIC_ATOMIC_INITIALIZER(-1);

static int checkFutexPrivateSupport()
{
    int value = 0;
#if defined(FUTEX_PRIVATE_FLAG)
    // check if the kernel supports extra futex flags
    // FUTEX_PRIVATE_FLAG appeared in v2.6.22
    Q_STATIC_ASSERT(FUTEX_PRIVATE_FLAG != 0x80000000);

    // try an operation that has no side-effects: wake up 42 threads
    // futex will return -1 (errno==ENOSYS) if the flag isn't supported
    // there should be no other error conditions
    value = syscall(__NR_futex, &futexFlagSupport,
                    FUTEX_WAKE | FUTEX_PRIVATE_FLAG,
                    42, 0, 0, 0);
Exemple #19
0
#include "qtextureglyphcache_gl_p.h"
#include "qpaintengineex_opengl2_p.h"
#include "private/qglengineshadersource_p.h"

#if defined QT_OPENGL_ES_2 && !defined(QT_NO_EGL)
#include "private/qeglcontext_p.h"
#endif

QT_BEGIN_NAMESPACE

#ifdef Q_WS_WIN
extern Q_GUI_EXPORT bool qt_cleartype_enabled;
#endif

QBasicAtomicInt qgltextureglyphcache_serial_number = Q_BASIC_ATOMIC_INITIALIZER(1);

QGLTextureGlyphCache::QGLTextureGlyphCache(const QGLContext *context, QFontEngineGlyphCache::Type type, const QTransform &matrix)
    : QImageTextureGlyphCache(type, matrix), QGLContextGroupResourceBase()
    , ctx(0)
    , pex(0)
    , m_blitProgram(0)
    , m_filterMode(Nearest)
    , m_serialNumber(qgltextureglyphcache_serial_number.fetchAndAddRelaxed(1))
{
#ifdef QT_GL_TEXTURE_GLYPH_CACHE_DEBUG
    qDebug(" -> QGLTextureGlyphCache() %p for context %p.", this, ctx);
#endif
    setContext(context);

    m_vertexCoordinateArray[0] = -1.0f;
Exemple #20
0
   \value Selected
        Display the pixmap when the item represented by the icon is
        selected.
*/

/*!
  \enum QIcon::State

  This enum describes the state for which a pixmap is intended to be
  used. The \e state can be:

  \value Off  Display the pixmap when the widget is in an "off" state
  \value On  Display the pixmap when the widget is in an "on" state
*/

static QBasicAtomicInt serialNumCounter = Q_BASIC_ATOMIC_INITIALIZER(1);

static void qt_cleanup_icon_cache();
namespace {
    struct IconCache : public QCache<QString, QIcon>
    {
        IconCache()
        {
            // ### note: won't readd if QApplication is re-created!
            qAddPostRoutine(qt_cleanup_icon_cache);
        }
    };
}

Q_GLOBAL_STATIC(IconCache, qtIconCache)
Exemple #21
0
#include "qmap.h"

#include <stdlib.h>

#ifdef QT_QMAP_DEBUG
# include <qstring.h>
# include <qvector.h>
#endif

QT_BEGIN_NAMESPACE

QMapData QMapData::shared_null = {
    &shared_null,
    { &shared_null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0, 0, false, true, false, 0
};

QMapData *QMapData::createData()
{
    return createData(0);
}

QMapData *QMapData::createData(int alignment)
{
    QMapData *d = new QMapData;
    Q_CHECK_PTR(d);
    Node *e = reinterpret_cast<Node *>(d);
    e->backward = e;
    e->forward[0] = e;
    d->ref = 1;
Exemple #22
0
#endif
#include <fcntl.h>
#include <unistd.h>

#ifndef Q_OS_WIN
#include <private/qcore_unix_p.h>
#endif

//#define QT_SHM_DEBUG

QT_BEGIN_NAMESPACE

#ifdef QT_POSIX_IPC
#include <QtCore/QAtomicInt>

static QBasicAtomicInt localUniqueId = Q_BASIC_ATOMIC_INITIALIZER(1);

static inline QByteArray makeKey(int id)
{
    return "/qwsshm_" + QByteArray::number(id, 16);
}
#endif

QWSSharedMemory::QWSSharedMemory()
    : shmId(-1), shmBase(0), shmSize(0)
#ifdef QT_POSIX_IPC
    , hand(-1)
#endif
{
}
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();
    }
}
Exemple #24
0
    IDNA and Punycode standards.

    To retrieve the name of the local host, use the static
    QHostInfo::localHostName() function.

    \note Since Qt 4.6.1 QHostInfo is using multiple threads for DNS lookup
    instead of one dedicated DNS thread. This improves performance,
    but also changes the order of signal emissions when using lookupHost()
    compared to previous versions of Qt.
    \note Since Qt 4.6.3 QHostInfo is using a small internal 60 second DNS cache
    for performance improvements.

    \sa QAbstractSocket, {http://www.rfc-editor.org/rfc/rfc3492.txt}{RFC 3492}
*/

static QBasicAtomicInt theIdCounter = Q_BASIC_ATOMIC_INITIALIZER(1);

/*!
    Looks up the IP address(es) associated with host name \a name, and
    returns an ID for the lookup. When the result of the lookup is
    ready, the slot or signal \a member in \a receiver is called with
    a QHostInfo argument. The QHostInfo object can then be inspected
    to get the results of the lookup.

    The lookup is performed by a single function call, for example:

    \snippet doc/src/snippets/code/src_network_kernel_qhostinfo.cpp 2

    The implementation of the slot prints basic information about the
    addresses returned by the lookup, or reports an error if it failed:
    for (i = 250; i <= 306; ++i)
        c.insert(i, 1000+i);
    for (i = 107; i <= 306; ++i) {
        QVERIFY(c.containsIndex(i));
        QCOMPARE(c.at(i), i < 250 ? i : 1000+i);
    }
}

struct RefCountingClassData
{
    QBasicAtomicInt ref;
    static RefCountingClassData shared_null;
};

RefCountingClassData RefCountingClassData::shared_null = {
    Q_BASIC_ATOMIC_INITIALIZER(1)
};

class RefCountingClass
{
public:
    RefCountingClass() : d(&RefCountingClassData::shared_null) { d->ref.ref(); }

    RefCountingClass(const RefCountingClass &other)
    {
        d = other.d;
        d->ref.ref();
    }

    ~RefCountingClass()
    {
Exemple #26
0
#endif
    struct flock flockData;
    flockData.l_type = F_WRLCK;
    flockData.l_whence = SEEK_SET;
    flockData.l_start = 0;
    flockData.l_len = 0; // 0 = entire file
    flockData.l_pid = getpid();
    if (fcntl(fd, F_SETLK, &flockData) == -1) // for networked filesystems
        return 0;
    return 1;
#else
    return 0;
#endif
}

static QBasicAtomicInt fcntlOK = Q_BASIC_ATOMIC_INITIALIZER(-1);

/*!
  \internal
  Checks that the OS isn't using POSIX locks to emulate flock().
  OS X is one of those.
*/
static bool fcntlWorksAfterFlock()
{
    int value = fcntlOK.load();
    if (Q_UNLIKELY(value == -1)) {
        value = QLockFilePrivate::checkFcntlWorksAfterFlock();
        fcntlOK.store(value);
    }
    return value == 1;
}
Exemple #27
0
    Returns the handle for this color map.
*/

/*!
    \fn void QGLColormap::setHandle(Qt::HANDLE handle)

    \internal

    Sets the handle for this color map to \a handle.
*/

#include "qglcolormap.h"

QT_BEGIN_NAMESPACE

QGLColormap::QGLColormapData QGLColormap::shared_null = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 };

/*!
    Construct a QGLColormap.
*/
QGLColormap::QGLColormap()
    : d(&shared_null)
{
    d->ref.ref();
}


/*!
    Construct a shallow copy of \a map.
*/
QGLColormap::QGLColormap(const QGLColormap &map)
Exemple #28
0
void qtsDebug(const char *fmt, ...)
{
    va_list va;
    va_start(va, fmt);

    fprintf(stderr, "QThreadStorage: ");
    vfprintf(stderr, fmt, va);
    fprintf(stderr, "\n");

    va_end(va);
}
#else
#  define DEBUG_MSG if(false)qDebug
#endif

static QBasicAtomicInt idCounter = Q_BASIC_ATOMIC_INITIALIZER(INT_MAX);
Q_GLOBAL_STATIC(QMutex, mutex)
typedef QMap<int, void (*)(void *)> DestructorMap;
Q_GLOBAL_STATIC(DestructorMap, destructors)

QThreadStorageData::QThreadStorageData(void (*func)(void *))
    : id(idCounter.fetchAndAddRelaxed(-1))
{
    QMutexLocker locker(mutex());
    destructors()->insert(id, func);

    DEBUG_MSG("QThreadStorageData: Allocated id %d, destructor %p", id, func);
}

QThreadStorageData::~QThreadStorageData()
{
    SixthBucketSize  = MaxTimerId - SixthBucketOffset
};

static const int BucketSize[] = {
    FirstBucketSize, SecondBucketSize, ThirdBucketSize,
    FourthBucketSize, FifthBucketSize, SixthBucketSize
};
enum { NumberOfBuckets = sizeof(BucketSize) / sizeof(BucketSize[0]) };

static const int BucketOffset[] = {
    FirstBucketOffset, SecondBucketOffset, ThirdBucketOffset,
    FourthBucketOffset, FifthBucketOffset, SixthBucketOffset
};

static QBasicAtomicPointer<int> timerIds[] =
    { Q_BASIC_ATOMIC_INITIALIZER(FirstBucket),
      Q_BASIC_ATOMIC_INITIALIZER(0),
      Q_BASIC_ATOMIC_INITIALIZER(0),
      Q_BASIC_ATOMIC_INITIALIZER(0),
      Q_BASIC_ATOMIC_INITIALIZER(0),
      Q_BASIC_ATOMIC_INITIALIZER(0) };

static void timerIdsDestructorFunction()
{
    // start at one, the first bucket is pre-allocated
    for (int i = 1; i < NumberOfBuckets; ++i)
        delete [] static_cast<int *>(timerIds[i]);
}
Q_DESTRUCTOR_FUNCTION(timerIdsDestructorFunction)

static QBasicAtomicInt nextFreeTimerId = Q_BASIC_ATOMIC_INITIALIZER(1);
Exemple #30
0
    static void ref() { contexts.ref(); }
    static void deref() {
        if (!contexts.deref()) {
            eglTerminate(QEgl::display());
            displayOpen = 0;
        }
    }
    static void setDisplayOpened() { displayOpen = 1; }
    static bool displayOpened() { return displayOpen; }

private:
    static QBasicAtomicInt contexts;
    static QBasicAtomicInt displayOpen;
};

QBasicAtomicInt QEglContextTracker::contexts = Q_BASIC_ATOMIC_INITIALIZER(0);
QBasicAtomicInt QEglContextTracker::displayOpen = Q_BASIC_ATOMIC_INITIALIZER(0);

// Current GL and VG contexts.  These are used to determine if
// we can avoid an eglMakeCurrent() after a call to lazyDoneCurrent().
// If a background thread modifies the value, the worst that will
// happen is a redundant eglMakeCurrent() in the foreground thread.
static QEglContext * volatile currentGLContext = 0;
static QEglContext * volatile currentVGContext = 0;

QEglContext::QEglContext()
    : apiType(QEgl::OpenGL)
    , ctx(EGL_NO_CONTEXT)
    , cfg(QEGL_NO_CONFIG)
    , currentSurface(EGL_NO_SURFACE)
    , current(false)