-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcoroutine_utils.cpp
506 lines (466 loc) · 12.8 KB
/
coroutine_utils.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
#include <QtCore/qprocess.h>
#ifdef Q_OS_WIN
#include <windows.h>
#else
#include <sys/wait.h>
#endif
#include "../include/coroutine_utils.h"
#include "../include/eventloop.h"
#include "debugger.h"
QTNG_LOGGER("qtng.coroutine");
QTNETWORKNG_NAMESPACE_BEGIN
bool LambdaFunctor::operator()()
{
callback();
return true;
}
class MarkDoneFunctor : public Functor
{
public:
MarkDoneFunctor(const QSharedPointer<Event> &done)
: done(done)
{
}
virtual bool operator()() override;
QSharedPointer<Event> done;
};
bool MarkDoneFunctor::operator()()
{
done->set();
return true;
}
DeferCallThread::DeferCallThread(std::function<void()> makeResult, QSharedPointer<Event> done,
EventLoopCoroutine *eventloop)
: makeResult(makeResult)
, done(done)
, eventloop(eventloop)
{
}
void DeferCallThread::run()
{
makeResult();
if (!eventloop.isNull()) {
eventloop->callLaterThreadSafe(100, new DeleteLaterFunctor<DeferCallThread>(this));
eventloop->callLaterThreadSafe(0, new MarkDoneFunctor(done));
}
}
class CoroutineThreadPrivate : public BaseCoroutine
{
public:
CoroutineThreadPrivate(quint32 capacity)
: BaseCoroutine(nullptr)
, tasks(capacity)
{
}
virtual void run() override;
public:
ThreadQueue<std::function<void()>> tasks;
};
void CoroutineThreadPrivate::run()
{
CoroutineGroup operations;
while (true) {
std::function<void()> f = tasks.get();
if (!f) {
return;
}
operations.spawn(f);
}
}
CoroutineThread::CoroutineThread(quint32 capacity)
: dd_ptr(new CoroutineThreadPrivate(capacity))
{
}
CoroutineThread::~CoroutineThread()
{
delete dd_ptr;
}
void CoroutineThread::run()
{
currentLoop()->getOrCreate()->runUntil(dd_ptr);
}
void CoroutineThread::apply(const std::function<void()> &f)
{
dd_ptr->tasks.put(f);
}
bool waitThread(QThread *thread)
{
if (!thread) {
return false;
}
if (thread->isFinished()) {
return true;
}
QSharedPointer<ThreadEvent> event(new ThreadEvent());
QMetaObject::Connection connection1 = QObject::connect(thread, &QThread::finished, [event] { event->set(); });
QMetaObject::Connection connection2 = QObject::connect(thread, &QThread::destroyed, [event] { event->set(); });
try {
bool result = event->tryWait();
QObject::disconnect(connection1);
QObject::disconnect(connection2);
return result;
} catch (...) {
QObject::disconnect(connection1);
QObject::disconnect(connection2);
throw;
}
}
bool waitProcess(QProcess *process)
{
if (!process) {
return false;
}
if (!EventLoopCoroutine::get()->isQt()) {
// fix a bug that the state of QProcesses is never changed if the qt eventloop is not run.
#ifdef Q_OS_UNIX
int pid = process->processId();
#else
HANDLE pid = process->pid() ? process->pid()->hProcess : NULL;
if (!pid) {
return false;
}
#endif
bool ok = callInThread<bool>([pid] {
#ifdef Q_OS_UNIX
int wstatus = 0;
return waitpid(pid, &wstatus, 0) == pid;
#else
return WaitForSingleObject(pid, -1) == WAIT_OBJECT_0;
#endif
});
// qt will print warning message: Destroyed while process ("/path/..") is still running.
// if (ok) {
// process->waitForFinished(0);
// }
return ok;
}
if (process->state() == QProcess::NotRunning) {
return true;
}
QSharedPointer<Event> event(new Event());
#if QT_VERSION < QT_VERSION_CHECK(5, 7, 0)
QScopedPointer<detail::SetEventHelper> helper(new detail::SetEventHelper(event));
QMetaObject::Connection connection = QObject::connect(process, SIGNAL(finished(int,QProcess::ExitStatus)),
helper.data(), SLOT(set()));
#else
QMetaObject::Connection connection = QObject::connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
[event](int, QProcess::ExitStatus) { event->set(); });
#endif
try {
bool result = event->tryWait();
QObject::disconnect(connection);
return result;
} catch (...) {
QObject::disconnect(connection);
throw;
}
}
CoroutineGroup::CoroutineGroup()
: QObject()
{
}
CoroutineGroup::~CoroutineGroup()
{
killall(true);
}
bool CoroutineGroup::add(QSharedPointer<Coroutine> coroutine, const QString &name)
{
if (!name.isEmpty()) {
if (!get(name).isNull()) {
return false;
}
coroutine->setObjectName(name);
}
QPointer<CoroutineGroup> self(this);
coroutine->finished.addCallback([self](BaseCoroutine *coroutine) {
if (self.isNull()) {
return;
}
self->deleteCoroutine(coroutine);
});
coroutines.append(coroutine);
return true;
}
QSharedPointer<Coroutine> CoroutineGroup::get(const QString &name)
{
QListIterator<QSharedPointer<Coroutine>> itor(coroutines);
while (itor.hasNext()) {
QSharedPointer<Coroutine> coroutine = itor.next();
if (coroutine->objectName() == name)
return coroutine;
}
return QSharedPointer<Coroutine>();
}
bool CoroutineGroup::has(const QString &name)
{
QListIterator<QSharedPointer<Coroutine>> itor(coroutines);
while (itor.hasNext()) {
QSharedPointer<Coroutine> coroutine = itor.next();
if (coroutine->objectName() == name) {
return true;
}
}
return false;
}
bool CoroutineGroup::isCurrent(const QString &name)
{
QListIterator<QSharedPointer<Coroutine>> itor(coroutines);
while (itor.hasNext()) {
QSharedPointer<Coroutine> coroutine = itor.next();
if (coroutine->objectName() == name && coroutine == Coroutine::current()) {
return true;
}
}
return false;
}
bool CoroutineGroup::kill(const QString &name, bool join)
{
QSharedPointer<Coroutine> found = get(name);
if (!found.isNull()) {
if (found.data() == Coroutine::current()) {
qtng_warning << "killing current coroutine?";
} else {
if (join) {
if (found->isRunning()) {
found->setPrevious(BaseCoroutine::current());
found->raise(new CoroutineExitException());
} else {
found->kill();
}
} else {
found->kill();
}
return true;
}
}
return false;
}
bool CoroutineGroup::killall(bool join)
{
bool done = false;
QList<QSharedPointer<Coroutine>> copy = coroutines;
if (join) {
BaseCoroutine *current = BaseCoroutine::current();
for (QSharedPointer<Coroutine> coroutine : copy) {
if (coroutine.data() == Coroutine::current()) {
continue;
}
if (coroutine->isRunning()) {
coroutine->setPrevious(current);
coroutine->raise(new CoroutineExitException());
} else {
coroutine->kill();
}
done = true;
}
} else {
for (QSharedPointer<Coroutine> coroutine : copy) {
if (coroutine.data() == Coroutine::current()) {
continue;
}
coroutine->kill();
done = true;
}
}
return done;
}
bool CoroutineGroup::join(const QString &name)
{
QSharedPointer<Coroutine> found = get(name);
if (!found.isNull()) {
if (found.data() == Coroutine::current()) {
qtng_warning << "joining current coroutine?";
} else {
found->join();
return true;
}
}
return false;
}
bool CoroutineGroup::joinall()
{
bool hasCoroutines = !coroutines.isEmpty();
QList<QSharedPointer<Coroutine>> copy = coroutines;
for (QSharedPointer<Coroutine> coroutine : copy) {
if (coroutine == Coroutine::current()) {
continue;
}
coroutine->join();
coroutines.removeOne(coroutine);
}
return hasCoroutines;
}
QSharedPointer<Coroutine> CoroutineGroup::any()
{
QSharedPointer<ValueEvent<QSharedPointer<Coroutine>>> event =
QSharedPointer<ValueEvent<QSharedPointer<Coroutine>>>::create();
QList<QPair<QWeakPointer<Coroutine>, int>> toRemove;
for (QSharedPointer<Coroutine> c : coroutines) {
QWeakPointer<Coroutine> cw = c.toWeakRef();
int callbackId = c->finished.addCallback([event, cw](BaseCoroutine *) { event->send(cw.toStrongRef()); });
toRemove.append(qMakePair(cw, callbackId));
}
try {
QSharedPointer<Coroutine> c = event->tryWait();
for (const QPair<QWeakPointer<Coroutine>, int> &item : toRemove) {
QSharedPointer<Coroutine> c = item.first.toStrongRef();
if (!c.isNull()) {
c->finished.remove(item.second);
}
}
return c;
} catch (...) {
for (const QPair<QWeakPointer<Coroutine>, int> &item : toRemove) {
QSharedPointer<Coroutine> c = item.first.toStrongRef();
if (!c.isNull()) {
c->finished.remove(item.second);
}
}
throw;
}
}
class DeleteCoroutineFunctor : public Functor
{
public:
virtual ~DeleteCoroutineFunctor() override;
virtual bool operator()() override;
QSharedPointer<BaseCoroutine> coroutine;
};
DeleteCoroutineFunctor::~DeleteCoroutineFunctor() { }
bool DeleteCoroutineFunctor::operator()()
{
return true;
}
void CoroutineGroup::deleteCoroutine(BaseCoroutine *baseCoroutine)
{
Coroutine *coroutine = dynamic_cast<Coroutine *>(baseCoroutine);
Q_ASSERT(coroutine != nullptr);
for (QList<QSharedPointer<Coroutine>>::iterator itor = coroutines.begin(); itor != coroutines.end(); ++itor) {
if (itor->data() == coroutine) {
DeleteCoroutineFunctor *callback = new DeleteCoroutineFunctor();
callback->coroutine = *itor;
EventLoopCoroutine::get()->callLater(0, callback);
coroutines.erase(itor);
break;
}
}
}
class ThreadPoolWorkItem
{
public:
ThreadPoolWorkItem()
: done(new Event())
{
}
std::function<void()> makeResult;
QSharedPointer<Event> done;
QPointer<EventLoopCoroutine> eventloop;
};
class ThreadPoolWorkThread : public QThread
{
public:
ThreadPoolWorkThread();
void call(std::function<void()> func);
void kill();
private:
virtual void run() override;
private:
QQueue<ThreadPoolWorkItem> queue;
QMutex mutex;
QWaitCondition hasWork;
QAtomicInteger<int> exiting;
};
ThreadPoolWorkThread::ThreadPoolWorkThread()
: exiting(false)
{
}
void ThreadPoolWorkThread::call(std::function<void()> func)
{
if (exiting.loadAcquire()) {
return;
}
ThreadPoolWorkItem item;
item.makeResult = func;
item.eventloop = EventLoopCoroutine::get();
mutex.lock();
queue.enqueue(item);
hasWork.wakeAll();
mutex.unlock();
item.done->tryWait();
}
void ThreadPoolWorkThread::kill()
{
mutex.lock();
hasWork.wakeAll();
exiting.storeRelease(true);
mutex.unlock();
wait();
}
void ThreadPoolWorkThread::run()
{
while (!exiting.loadAcquire()) {
mutex.lock();
if (queue.isEmpty()) {
hasWork.wait(&mutex);
if (queue.isEmpty() || exiting.loadAcquire()) {
mutex.unlock();
return;
}
}
const ThreadPoolWorkItem &item = queue.takeFirst();
mutex.unlock();
if (item.eventloop.isNull()) {
return;
}
item.makeResult();
if (!item.eventloop.isNull()) {
item.eventloop->callLaterThreadSafe(0, new MarkDoneFunctor(item.done));
}
}
}
ThreadPool::ThreadPool(int threads)
{
if (threads <= 0) {
semaphore.reset(new Semaphore(QThread::idealThreadCount() * 2 + 1));
} else {
semaphore.reset(new Semaphore(threads));
}
}
ThreadPool::~ThreadPool()
{
for (QSharedPointer<ThreadPoolWorkThread> thread : threads) {
thread->kill();
}
}
void ThreadPool::call(std::function<void()> func)
{
QSharedPointer<Semaphore> semaphore(this->semaphore);
ScopedLock<Semaphore> lock(*semaphore);
if (!lock.isSuccess()) {
return;
}
QSharedPointer<ThreadPoolWorkThread> thread;
if (threads.isEmpty()) {
thread.reset(new ThreadPoolWorkThread());
thread->start(QThread::LowPriority);
} else {
thread = threads.takeFirst();
}
QPointer<ThreadPool> self(this);
try {
thread->call(func);
if (self) {
threads.append(thread);
} else {
thread->kill();
}
} catch (...) {
if (self) {
threads.append(thread);
} else {
thread->kill();
}
throw;
}
}
QTNETWORKNG_NAMESPACE_END