File indexing completed on 2024-04-28 15:34:48
0001 /* -*- C++ -*- 0002 This file contains a testsuite for global queue customizations in ThreadWeaver. 0003 0004 SPDX-FileCopyrightText: 2005-2013 Mirko Boehm <mirko@kde.org> 0005 0006 SPDX-License-Identifier: LGPL-2.0-or-later 0007 */ 0008 0009 #include <QString> 0010 #include <QTest> 0011 0012 #include <ThreadWeaver/IdDecorator> 0013 #include <ThreadWeaver/Queue> 0014 #include <ThreadWeaver/QueueSignals> 0015 #include <ThreadWeaver/ThreadWeaver> 0016 #include <weaver.h> 0017 0018 using namespace ThreadWeaver; 0019 QAtomicInt counter; 0020 0021 class CountingJobDecorator : public IdDecorator 0022 { 0023 public: 0024 explicit CountingJobDecorator(const JobPointer &job) 0025 : IdDecorator(job.data(), false) 0026 , original_(job) 0027 { 0028 } 0029 0030 void run(JobPointer self, Thread *thread) override 0031 { 0032 counter.fetchAndAddRelease(1); 0033 IdDecorator::run(self, thread); 0034 counter.fetchAndAddAcquire(1); 0035 } 0036 0037 JobPointer original_; 0038 }; 0039 0040 class JobCountingWeaver : public Weaver 0041 { 0042 Q_OBJECT 0043 public: 0044 explicit JobCountingWeaver(QObject *parent = nullptr) 0045 : Weaver(parent) 0046 { 0047 } 0048 void enqueue(const QVector<JobPointer> &jobs) override 0049 { 0050 QVector<JobPointer> decorated; 0051 std::transform(jobs.begin(), jobs.end(), std::back_inserter(decorated), [](const JobPointer &job) { 0052 return JobPointer(new CountingJobDecorator(job)); 0053 }); 0054 Weaver::enqueue(decorated); 0055 } 0056 }; 0057 0058 class CountingGlobalQueueFactory : public Queue::GlobalQueueFactory 0059 { 0060 Queue *create(QObject *parent = nullptr) override 0061 { 0062 return new Queue(new JobCountingWeaver, parent); 0063 } 0064 }; 0065 0066 int argc = 0; 0067 0068 class QueueFactoryTests : public QObject 0069 { 0070 Q_OBJECT 0071 private Q_SLOTS: 0072 void testQueueFactory() 0073 { 0074 counter.storeRelease(0); 0075 QCoreApplication app(argc, (char **)nullptr); 0076 Queue queue(new JobCountingWeaver(this)); 0077 queue.enqueue(make_job([]() {})); // nop 0078 queue.finish(); 0079 QCOMPARE(counter.loadAcquire(), 2); 0080 } 0081 0082 void testGlobalQueueFactory() 0083 { 0084 Queue::setGlobalQueueFactory(new CountingGlobalQueueFactory()); 0085 QCoreApplication app(argc, (char **)nullptr); 0086 counter.storeRelease(0); 0087 Queue::instance()->enqueue(make_job([]() {})); // nop 0088 Queue::instance()->finish(); 0089 QCOMPARE(counter.loadAcquire(), 2); 0090 } 0091 }; 0092 0093 QTEST_APPLESS_MAIN(QueueFactoryTests) 0094 0095 #include "QueueFactoryTests.moc"