/
mthreadpool.cpp
588 lines (517 loc) · 17.3 KB
/
mthreadpool.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/* -*- Mode: c++ -*-
*
* Class MThreadPool
*
* Copyright (C) Daniel Kristjansson 2011
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** \defgroup mthreadpool MThreadPool
* \ingroup libmythbase
* \brief Framework for managing threads.
*
* Commit 47d67e6722 added two new classes MThread and MThreadPool to be used
* instead of QThread and QThreadPool. These mirror the API's of the Qt classes
* but also add a requirement for a QString naming the thread or naming the
* runnable which are used for debugging. These wrappers also make sure mysql
* connections are torn down properly and have a number of safety checks and
* assurances. The destructor for MThread also makes sure that a thread has
* stopped running before we allow the QThread to be deleted. And MThreaPool
* makes sure all it's threads have stopped running. MThread has a Cleanup()
* method that attempts to shut down any threads that are running, it only
* works for threads that exit on a call to exit(), which includes any threads
* using the Qt event loop. It will also print out the names of the threads
* that are still running for debugging purposes.
*
* MThread has one special constructor. It takes a QRunnable* and runs it
* instead of the Qt event loop in the default run() implementation. Unlike
* MThreadPool and QThreadPool, MThread does not delete this runnable when it
* exits. This allows you to run something with less boilerplate code. Just
* like with QThread in Qt4 it really is better to use the Qt event loop rather
* than write your own. As you don't use the Qt event loop QObject
* deleteLater's are not executed until the thread exits, Qt events and timers
* do not work making Qt networking classes misbehave and signals/slots are
* generally unsafe. However, many of the threads with event loops in MythTV
* were written before Qt allowed an event loop outside the main thread so this
* syntactic sugar just lets us handle that with less lines of code.
*
* There are a few other differences with respect to Qt's classes other than
* requiring a name.
*
* \li MThread does not inherit from QObject, if you need QObject services
* in a threading class you will need to inherit from QObject separately. Note
* when you inherit from QObject, you must inherit from no more than one
* QObject based class and it must be first in the list of classes your class
* inherits from (a Qt restriction).
*
* \li QThread doesn't implement most of QThread's static methods, notably
* QThread::currentThread(). It does make the underlying QThread available via
* the qthread() method. But the usual reason to use QThread::currentThread()
* is to check which thread you are running in. For this there is a set of
* helper functions is_current_thread(MThread&), is_current_thread(QThread*),
* and is_current_thread(MThread*) which you can use instead.
*
* \li MThreadPool does not have reserveThread() and releaseThread()
* calls; instead use startReserved(). The reserveThread() and releaseThread()
* API is not a good API because it doesn't ensure that your runnable starts
* right away even though the thread will eventually not be counted amoung
* those forcing other threads to go to the queue rather than running right
* away.
*/
// C++ headers
#include <algorithm>
// Qt headers
#include <QCoreApplication>
#include <QList>
#include <QMap>
#include <QMutex>
#include <QMutexLocker>
#include <QPair>
#include <QRunnable>
#include <QSet>
#include <QWaitCondition>
#include <utility>
// MythTV headers
#include "mthreadpool.h"
#include "mythlogging.h"
#include "mythtimer.h"
#include "logging.h"
#include "mthread.h"
#include "mythdb.h"
using MPoolEntry = QPair<QRunnable*,QString>;
using MPoolQueue = QList<MPoolEntry>;
using MPoolQueues = QMap<int, MPoolQueue>;
class MPoolThread : public MThread
{
public:
MPoolThread(MThreadPool &pool, int timeout) :
MThread("PT"), m_pool(pool), m_expiryTimeout(timeout)
{
QMutexLocker locker(&s_lock);
setObjectName(QString("PT%1").arg(s_thread_num));
s_thread_num++;
}
void run(void) override // MThread
{
RunProlog();
MythTimer t;
t.start();
QMutexLocker locker(&m_lock);
while (true)
{
if (m_doRun && !m_runnable)
m_wait.wait(locker.mutex(), m_expiryTimeout+1);
if (!m_runnable)
{
m_doRun = false;
locker.unlock();
m_pool.NotifyDone(this);
locker.relock();
break;
}
if (!m_runnableName.isEmpty())
loggingRegisterThread(m_runnableName);
bool autodelete = m_runnable->autoDelete();
m_runnable->run();
if (autodelete)
delete m_runnable;
if (m_reserved)
m_pool.ReleaseThread();
m_reserved = false;
m_runnable = nullptr;
loggingDeregisterThread();
loggingRegisterThread(objectName());
GetMythDB()->GetDBManager()->PurgeIdleConnections(false);
qApp->processEvents();
qApp->sendPostedEvents(nullptr, QEvent::DeferredDelete);
t.start();
if (m_doRun)
{
locker.unlock();
m_pool.NotifyAvailable(this);
locker.relock();
}
else
{
locker.unlock();
m_pool.NotifyDone(this);
locker.relock();
break;
}
}
RunEpilog();
}
bool SetRunnable(QRunnable *runnable, QString runnableName,
bool reserved)
{
QMutexLocker locker(&m_lock);
if (m_doRun && (m_runnable == nullptr))
{
m_runnable = runnable;
m_runnableName = std::move(runnableName);
m_reserved = reserved;
m_wait.wakeAll();
return true;
}
return false;
}
void Shutdown(void)
{
QMutexLocker locker(&m_lock);
m_doRun = false;
m_wait.wakeAll();
}
QMutex m_lock;
QWaitCondition m_wait;
MThreadPool &m_pool;
int m_expiryTimeout;
bool m_doRun {true};
QString m_runnableName;
bool m_reserved {false};
static QMutex s_lock;
static uint s_thread_num;
};
QMutex MPoolThread::s_lock;
uint MPoolThread::s_thread_num = 0;
//////////////////////////////////////////////////////////////////////
class MThreadPoolPrivate
{
public:
explicit MThreadPoolPrivate(QString name) :
m_name(std::move(name)) {}
int GetRealMaxThread(void) const
{
return std::max(m_maxThreadCount,1) + m_reserveThread;
}
mutable QMutex m_lock;
QString m_name;
QWaitCondition m_wait;
bool m_running {true};
int m_expiryTimeout {120 * 1000};
int m_maxThreadCount {QThread::idealThreadCount()};
int m_reserveThread {0};
MPoolQueues m_runQueues;
QSet<MPoolThread*> m_availThreads;
QSet<MPoolThread*> m_runningThreads;
QList<MPoolThread*> m_deleteThreads;
static QMutex s_pool_lock;
static MThreadPool *s_pool;
static QList<MThreadPool*> s_all_pools;
};
QMutex MThreadPoolPrivate::s_pool_lock(QMutex::Recursive);
MThreadPool *MThreadPoolPrivate::s_pool = nullptr;
QList<MThreadPool*> MThreadPoolPrivate::s_all_pools;
//////////////////////////////////////////////////////////////////////
MThreadPool::MThreadPool(const QString &name) :
m_priv(new MThreadPoolPrivate(name))
{
QMutexLocker locker(&MThreadPoolPrivate::s_pool_lock);
MThreadPoolPrivate::s_all_pools.push_back(this);
}
MThreadPool::~MThreadPool()
{
Stop();
DeletePoolThreads();
{
QMutexLocker locker(&MThreadPoolPrivate::s_pool_lock);
MThreadPoolPrivate::s_all_pools.removeAll(this);
}
delete m_priv;
m_priv = nullptr;
}
void MThreadPool::Stop(void)
{
QMutexLocker locker(&m_priv->m_lock);
m_priv->m_running = false;
QSet<MPoolThread*>::iterator it = m_priv->m_availThreads.begin();
for (; it != m_priv->m_availThreads.end(); ++it)
(*it)->Shutdown();
it = m_priv->m_runningThreads.begin();
for (; it != m_priv->m_runningThreads.end(); ++it)
(*it)->Shutdown();
m_priv->m_wait.wakeAll();
}
void MThreadPool::DeletePoolThreads(void)
{
waitForDone();
QMutexLocker locker(&m_priv->m_lock);
for (auto *thread : qAsConst(m_priv->m_availThreads))
{
m_priv->m_deleteThreads.push_front(thread);
}
m_priv->m_availThreads.clear();
while (!m_priv->m_deleteThreads.empty())
{
MPoolThread *thread = m_priv->m_deleteThreads.back();
locker.unlock();
thread->wait();
locker.relock();
delete thread;
if (m_priv->m_deleteThreads.back() == thread)
m_priv->m_deleteThreads.pop_back();
else
m_priv->m_deleteThreads.removeAll(thread);
}
}
MThreadPool *MThreadPool::globalInstance(void)
{
QMutexLocker locker(&MThreadPoolPrivate::s_pool_lock);
if (!MThreadPoolPrivate::s_pool)
MThreadPoolPrivate::s_pool = new MThreadPool("GlobalPool");
return MThreadPoolPrivate::s_pool;
}
void MThreadPool::StopAllPools(void)
{
QMutexLocker locker(&MThreadPoolPrivate::s_pool_lock);
QList<MThreadPool*>::iterator it;
for (it = MThreadPoolPrivate::s_all_pools.begin();
it != MThreadPoolPrivate::s_all_pools.end(); ++it)
{
(*it)->Stop();
}
}
void MThreadPool::ShutdownAllPools(void)
{
QMutexLocker locker(&MThreadPoolPrivate::s_pool_lock);
QList<MThreadPool*>::iterator it;
for (it = MThreadPoolPrivate::s_all_pools.begin();
it != MThreadPoolPrivate::s_all_pools.end(); ++it)
{
(*it)->Stop();
}
for (it = MThreadPoolPrivate::s_all_pools.begin();
it != MThreadPoolPrivate::s_all_pools.end(); ++it)
{
(*it)->DeletePoolThreads();
}
}
void MThreadPool::start(QRunnable *runnable, const QString& debugName, int priority)
{
QMutexLocker locker(&m_priv->m_lock);
if (TryStartInternal(runnable, debugName, false))
return;
MPoolQueues::iterator it = m_priv->m_runQueues.find(priority);
if (it != m_priv->m_runQueues.end())
{
(*it).push_back(MPoolEntry(runnable,debugName));
}
else
{
MPoolQueue list;
list.push_back(MPoolEntry(runnable,debugName));
m_priv->m_runQueues[priority] = list;
}
}
void MThreadPool::startReserved(
QRunnable *runnable, const QString& debugName, int waitForAvailMS)
{
QMutexLocker locker(&m_priv->m_lock);
if (waitForAvailMS > 0 && m_priv->m_availThreads.empty() &&
m_priv->m_runningThreads.size() >= m_priv->m_maxThreadCount)
{
MythTimer t;
t.start();
int left = waitForAvailMS - t.elapsed();
while (left > 0 && m_priv->m_availThreads.empty() &&
m_priv->m_runningThreads.size() >= m_priv->m_maxThreadCount)
{
m_priv->m_wait.wait(locker.mutex(), left);
left = waitForAvailMS - t.elapsed();
}
}
TryStartInternal(runnable, debugName, true);
}
bool MThreadPool::tryStart(QRunnable *runnable, const QString& debugName)
{
QMutexLocker locker(&m_priv->m_lock);
return TryStartInternal(runnable, debugName, false);
}
bool MThreadPool::TryStartInternal(
QRunnable *runnable, const QString& debugName, bool reserved)
{
if (!m_priv->m_running)
return false;
while (!m_priv->m_deleteThreads.empty())
{
m_priv->m_deleteThreads.back()->wait();
delete m_priv->m_deleteThreads.back();
m_priv->m_deleteThreads.pop_back();
}
while (m_priv->m_availThreads.begin() != m_priv->m_availThreads.end())
{
MPoolThread *thread = *m_priv->m_availThreads.begin();
m_priv->m_availThreads.erase(m_priv->m_availThreads.begin());
m_priv->m_runningThreads.insert(thread);
if (reserved)
m_priv->m_reserveThread++;
if (thread->SetRunnable(runnable, debugName, reserved))
{
return true;
}
if (reserved)
m_priv->m_reserveThread--;
thread->Shutdown();
m_priv->m_runningThreads.remove(thread);
m_priv->m_deleteThreads.push_front(thread);
}
if (reserved ||
m_priv->m_runningThreads.size() < m_priv->GetRealMaxThread())
{
if (reserved)
m_priv->m_reserveThread++;
auto *thread = new MPoolThread(*this, m_priv->m_expiryTimeout);
m_priv->m_runningThreads.insert(thread);
thread->SetRunnable(runnable, debugName, reserved);
thread->start();
if (thread->isRunning())
{
return true;
}
// Thread failed to run, OOM?
// QThread will print an error, so we don't have to
if (reserved)
m_priv->m_reserveThread--;
thread->Shutdown();
m_priv->m_runningThreads.remove(thread);
m_priv->m_deleteThreads.push_front(thread);
}
return false;
}
void MThreadPool::NotifyAvailable(MPoolThread *thread)
{
QMutexLocker locker(&m_priv->m_lock);
if (!m_priv->m_running)
{
m_priv->m_runningThreads.remove(thread);
thread->Shutdown();
m_priv->m_deleteThreads.push_front(thread);
m_priv->m_wait.wakeAll();
return;
}
MPoolQueues::iterator it = m_priv->m_runQueues.begin();
if (it == m_priv->m_runQueues.end())
{
m_priv->m_runningThreads.remove(thread);
m_priv->m_availThreads.insert(thread);
m_priv->m_wait.wakeAll();
return;
}
MPoolEntry e = (*it).front();
if (!thread->SetRunnable(e.first, e.second, false))
{
m_priv->m_runningThreads.remove(thread);
m_priv->m_wait.wakeAll();
if (!TryStartInternal(e.first, e.second, false))
{
thread->Shutdown();
m_priv->m_deleteThreads.push_front(thread);
return;
}
thread->Shutdown();
m_priv->m_deleteThreads.push_front(thread);
}
(*it).pop_front();
if ((*it).empty())
m_priv->m_runQueues.erase(it);
}
void MThreadPool::NotifyDone(MPoolThread *thread)
{
QMutexLocker locker(&m_priv->m_lock);
m_priv->m_runningThreads.remove(thread);
m_priv->m_availThreads.remove(thread);
if (!m_priv->m_deleteThreads.contains(thread))
m_priv->m_deleteThreads.push_front(thread);
m_priv->m_wait.wakeAll();
}
int MThreadPool::expiryTimeout(void) const
{
QMutexLocker locker(&m_priv->m_lock);
return m_priv->m_expiryTimeout;
}
void MThreadPool::setExpiryTimeout(int expiryTimeout)
{
QMutexLocker locker(&m_priv->m_lock);
m_priv->m_expiryTimeout = expiryTimeout;
}
int MThreadPool::maxThreadCount(void) const
{
QMutexLocker locker(&m_priv->m_lock);
return m_priv->m_maxThreadCount;
}
void MThreadPool::setMaxThreadCount(int maxThreadCount)
{
QMutexLocker locker(&m_priv->m_lock);
m_priv->m_maxThreadCount = maxThreadCount;
}
int MThreadPool::activeThreadCount(void) const
{
QMutexLocker locker(&m_priv->m_lock);
return m_priv->m_availThreads.size() + m_priv->m_runningThreads.size();
}
/*
void MThreadPool::reserveThread(void)
{
QMutexLocker locker(&m_priv->m_lock);
m_priv->m_reserveThread++;
}
void MThreadPool::releaseThread(void)
{
QMutexLocker locker(&m_priv->m_lock);
if (m_priv->m_reserveThread > 0)
m_priv->m_reserveThread--;
}
*/
void MThreadPool::ReleaseThread(void)
{
QMutexLocker locker(&m_priv->m_lock);
if (m_priv->m_reserveThread > 0)
m_priv->m_reserveThread--;
}
#if 0
static void print_set(QString title, QSet<MPoolThread*> set)
{
LOG(VB_GENERAL, LOG_INFO, title);
for (auto item : qAsConst(set))
{
LOG(VB_GENERAL, LOG_INFO, QString(" : 0x%1")
.arg((quint64)item,0,16));
}
LOG(VB_GENERAL, LOG_INFO, "");
}
#endif
void MThreadPool::waitForDone(void)
{
QMutexLocker locker(&m_priv->m_lock);
while (true)
{
while (!m_priv->m_deleteThreads.empty())
{
m_priv->m_deleteThreads.back()->wait();
delete m_priv->m_deleteThreads.back();
m_priv->m_deleteThreads.pop_back();
}
if (m_priv->m_running && !m_priv->m_runQueues.empty())
{
m_priv->m_wait.wait(locker.mutex());
continue;
}
QSet<MPoolThread*> working = m_priv->m_runningThreads;
working = working.subtract(m_priv->m_availThreads);
if (working.empty())
break;
m_priv->m_wait.wait(locker.mutex());
}
}
/* vim: set expandtab tabstop=4 shiftwidth=4: */