File indexing completed on 2024-05-19 04:39:58
0001 /* 0002 SPDX-FileCopyrightText: 2010 Milian Wolff <mail@milianw.de> 0003 0004 SPDX-License-Identifier: GPL-2.0-or-later 0005 */ 0006 0007 #include "test_foregroundlock.h" 0008 0009 #include <QTest> 0010 #include <QStandardPaths> 0011 #include <QThread> 0012 #include <QRandomGenerator> 0013 0014 #include <memory> 0015 #include <vector> 0016 0017 #include "../foregroundlock.h" 0018 0019 QTEST_MAIN(KDevelop::TestForegroundLock) 0020 0021 using namespace KDevelop; 0022 0023 //BEGIN Helper Threads 0024 0025 class TryLockThread : public QThread 0026 { 0027 Q_OBJECT 0028 0029 public: 0030 void run() override 0031 { 0032 ForegroundLock lock(false); 0033 auto* randomGenerator = QRandomGenerator::global(); 0034 for (int i = 0; i < 1000; ++i) { 0035 if (lock.tryLock()) { 0036 lock.unlock(); 0037 } 0038 QThread::usleep(randomGenerator->bounded(20)); 0039 } 0040 } 0041 }; 0042 0043 void TestForegroundLock::initTestCase() 0044 { 0045 QStandardPaths::setTestModeEnabled(true); 0046 } 0047 0048 void TestForegroundLock::testTryLock_data() 0049 { 0050 QTest::addColumn<int>("numThreads"); 0051 for (int i = 1; i <= 10; ++i) { 0052 QTest::newRow(qPrintable(QString::number(i))) << i; 0053 } 0054 } 0055 0056 void TestForegroundLock::testTryLock() 0057 { 0058 QFETCH(int, numThreads); 0059 std::vector<std::unique_ptr<TryLockThread>> threads; 0060 threads.reserve(numThreads); 0061 for (int i = 0; i < numThreads; ++i) { 0062 threads.push_back(std::make_unique<TryLockThread>()); 0063 } 0064 0065 ForegroundLock lock(true); 0066 0067 for (auto& thread : threads) { 0068 thread->start(); 0069 } 0070 0071 lock.unlock(); 0072 0073 while (true) { 0074 const bool running 0075 = std::any_of(threads.cbegin(), threads.cend(), [](const auto& thread) { return thread->isRunning(); }); 0076 0077 if (!running) { 0078 break; 0079 } 0080 lock.relock(); 0081 QThread::usleep(10); 0082 lock.unlock(); 0083 } 0084 } 0085 0086 #include "moc_test_foregroundlock.cpp" 0087 #include "test_foregroundlock.moc"