1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
// SPDX-FileCopyrightText: 2016 - 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#include "ut_singleton.h"
#include <gtest/gtest.h>
#include <QTest>
#include <QThread>
Singleton::Singleton(QObject *parent)
: QObject(parent),
count(0)
{
}
MultiSingletonTester::MultiSingletonTester(QObject *parent)
: QObject(parent)
{
}
void MultiSingletonTester::run()
{
Singleton::ref().count.ref();
}
int MultiSingletonTester::count() const
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
return Singleton::ref().count.loadRelaxed();
#else
return Singleton::ref().count.load();
#endif
}
TEST(ut_DSingleton, testDSingleton)
{
const int exampleCount = 5;
QVector<QThread*> threads;
QVector<MultiSingletonTester*> testers;
threads.reserve(exampleCount);
testers.reserve(exampleCount);
for (int i = 0; i < exampleCount; i++) {
auto thread = new QThread();
auto tester = new MultiSingletonTester;
tester->moveToThread(thread);
QObject::connect(thread, &QThread::started, tester, &MultiSingletonTester::run);
threads.push_back(thread);
testers.push_back(tester);
thread->start();
}
for (auto thread : threads) {
thread->quit();
}
ASSERT_TRUE(QTest::qWaitFor([threads] {
for (auto thread : threads) {
if (!thread->isFinished()) {
return false;
}
}
return true;
}));
for (auto tester : testers) {
ASSERT_EQ(tester->count(), exampleCount);
}
qDeleteAll(threads);
qDeleteAll(testers);
}
|