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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include <thread>
#include <folly/Exception.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/FutureExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/executors/ThreadPoolExecutor.h>
#include <folly/executors/task_queue/LifoSemMPMCQueue.h>
#include <folly/executors/task_queue/UnboundedBlockingQueue.h>
#include <folly/executors/thread_factory/PriorityThreadFactory.h>
#include <folly/portability/GTest.h>
using namespace folly;
using namespace std::chrono;
static Func burnMs(uint64_t ms) {
return [ms]() { std::this_thread::sleep_for(milliseconds(ms)); };
}
template <class TPE>
static void basic() {
// Create and destroy
TPE tpe(10);
}
TEST(ThreadPoolExecutorTest, CPUBasic) {
basic<CPUThreadPoolExecutor>();
}
TEST(IOThreadPoolExecutorTest, IOBasic) {
basic<IOThreadPoolExecutor>();
}
template <class TPE>
static void resize() {
TPE tpe(100);
EXPECT_EQ(100, tpe.numThreads());
tpe.setNumThreads(50);
EXPECT_EQ(50, tpe.numThreads());
tpe.setNumThreads(150);
EXPECT_EQ(150, tpe.numThreads());
}
TEST(ThreadPoolExecutorTest, CPUResize) {
resize<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOResize) {
resize<IOThreadPoolExecutor>();
}
template <class TPE>
static void stop() {
TPE tpe(1);
std::atomic<int> completed(0);
auto f = [&]() {
burnMs(10)();
completed++;
};
for (int i = 0; i < 1000; i++) {
tpe.add(f);
}
tpe.stop();
EXPECT_GT(1000, completed);
}
// IOThreadPoolExecutor's stop() behaves like join(). Outstanding tasks belong
// to the event base, will be executed upon its destruction, and cannot be
// taken back.
template <>
void stop<IOThreadPoolExecutor>() {
IOThreadPoolExecutor tpe(1);
std::atomic<int> completed(0);
auto f = [&]() {
burnMs(10)();
completed++;
};
for (int i = 0; i < 10; i++) {
tpe.add(f);
}
tpe.stop();
EXPECT_EQ(10, completed);
}
TEST(ThreadPoolExecutorTest, CPUStop) {
stop<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOStop) {
stop<IOThreadPoolExecutor>();
}
template <class TPE>
static void join() {
TPE tpe(10);
std::atomic<int> completed(0);
auto f = [&]() {
burnMs(1)();
completed++;
};
for (int i = 0; i < 1000; i++) {
tpe.add(f);
}
tpe.join();
EXPECT_EQ(1000, completed);
}
TEST(ThreadPoolExecutorTest, CPUJoin) {
join<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOJoin) {
join<IOThreadPoolExecutor>();
}
template <class TPE>
static void resizeUnderLoad() {
TPE tpe(10);
std::atomic<int> completed(0);
auto f = [&]() {
burnMs(1)();
completed++;
};
for (int i = 0; i < 1000; i++) {
tpe.add(f);
}
tpe.setNumThreads(5);
tpe.setNumThreads(15);
tpe.join();
EXPECT_EQ(1000, completed);
}
TEST(ThreadPoolExecutorTest, CPUResizeUnderLoad) {
resizeUnderLoad<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOResizeUnderLoad) {
resizeUnderLoad<IOThreadPoolExecutor>();
}
template <class TPE>
static void poolStats() {
folly::Baton<> startBaton, endBaton;
TPE tpe(1);
auto stats = tpe.getPoolStats();
EXPECT_EQ(1, stats.threadCount);
EXPECT_EQ(1, stats.idleThreadCount);
EXPECT_EQ(0, stats.activeThreadCount);
EXPECT_EQ(0, stats.pendingTaskCount);
EXPECT_EQ(0, tpe.getPendingTaskCount());
EXPECT_EQ(0, stats.totalTaskCount);
tpe.add([&]() {
startBaton.post();
endBaton.wait();
});
tpe.add([&]() {});
startBaton.wait();
stats = tpe.getPoolStats();
EXPECT_EQ(1, stats.threadCount);
EXPECT_EQ(0, stats.idleThreadCount);
EXPECT_EQ(1, stats.activeThreadCount);
EXPECT_EQ(1, stats.pendingTaskCount);
EXPECT_EQ(1, tpe.getPendingTaskCount());
EXPECT_EQ(2, stats.totalTaskCount);
endBaton.post();
}
TEST(ThreadPoolExecutorTest, CPUPoolStats) {
poolStats<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOPoolStats) {
poolStats<IOThreadPoolExecutor>();
}
template <class TPE>
static void taskStats() {
TPE tpe(1);
std::atomic<int> c(0);
tpe.subscribeToTaskStats([&](ThreadPoolExecutor::TaskStats stats) {
int i = c++;
EXPECT_LT(milliseconds(0), stats.runTime);
if (i == 1) {
EXPECT_LT(milliseconds(0), stats.waitTime);
}
});
tpe.add(burnMs(10));
tpe.add(burnMs(10));
tpe.join();
EXPECT_EQ(2, c);
}
TEST(ThreadPoolExecutorTest, CPUTaskStats) {
taskStats<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOTaskStats) {
taskStats<IOThreadPoolExecutor>();
}
template <class TPE>
static void expiration() {
TPE tpe(1);
std::atomic<int> statCbCount(0);
tpe.subscribeToTaskStats([&](ThreadPoolExecutor::TaskStats stats) {
int i = statCbCount++;
if (i == 0) {
EXPECT_FALSE(stats.expired);
} else if (i == 1) {
EXPECT_TRUE(stats.expired);
} else {
FAIL();
}
});
std::atomic<int> expireCbCount(0);
auto expireCb = [&]() { expireCbCount++; };
tpe.add(burnMs(10), seconds(60), expireCb);
tpe.add(burnMs(10), milliseconds(10), expireCb);
tpe.join();
EXPECT_EQ(2, statCbCount);
EXPECT_EQ(1, expireCbCount);
}
TEST(ThreadPoolExecutorTest, CPUExpiration) {
expiration<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOExpiration) {
expiration<IOThreadPoolExecutor>();
}
template <typename TPE>
static void futureExecutor() {
FutureExecutor<TPE> fe(2);
std::atomic<int> c{0};
fe.addFuture([]() { return makeFuture<int>(42); }).then([&](Try<int>&& t) {
c++;
EXPECT_EQ(42, t.value());
});
fe.addFuture([]() { return 100; }).then([&](Try<int>&& t) {
c++;
EXPECT_EQ(100, t.value());
});
fe.addFuture([]() { return makeFuture(); }).then([&](Try<Unit>&& t) {
c++;
EXPECT_NO_THROW(t.value());
});
fe.addFuture([]() { return; }).then([&](Try<Unit>&& t) {
c++;
EXPECT_NO_THROW(t.value());
});
fe.addFuture([]() { throw std::runtime_error("oops"); })
.then([&](Try<Unit>&& t) {
c++;
EXPECT_THROW(t.value(), std::runtime_error);
});
// Test doing actual async work
folly::Baton<> baton;
fe.addFuture([&]() {
auto p = std::make_shared<Promise<int>>();
std::thread t([p]() {
burnMs(10)();
p->setValue(42);
});
t.detach();
return p->getFuture();
})
.then([&](Try<int>&& t) {
EXPECT_EQ(42, t.value());
c++;
baton.post();
});
baton.wait();
fe.join();
EXPECT_EQ(6, c);
}
TEST(ThreadPoolExecutorTest, CPUFuturePool) {
futureExecutor<CPUThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, IOFuturePool) {
futureExecutor<IOThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, PriorityPreemptionTest) {
bool tookLopri = false;
auto completed = 0;
auto hipri = [&] {
EXPECT_FALSE(tookLopri);
completed++;
};
auto lopri = [&] {
tookLopri = true;
completed++;
};
CPUThreadPoolExecutor pool(0, 2);
for (int i = 0; i < 50; i++) {
pool.addWithPriority(lopri, Executor::LO_PRI);
}
for (int i = 0; i < 50; i++) {
pool.addWithPriority(hipri, Executor::HI_PRI);
}
pool.setNumThreads(1);
pool.join();
EXPECT_EQ(100, completed);
}
class TestObserver : public ThreadPoolExecutor::Observer {
public:
void threadStarted(ThreadPoolExecutor::ThreadHandle*) override {
threads_++;
}
void threadStopped(ThreadPoolExecutor::ThreadHandle*) override {
threads_--;
}
void threadPreviouslyStarted(ThreadPoolExecutor::ThreadHandle*) override {
threads_++;
}
void threadNotYetStopped(ThreadPoolExecutor::ThreadHandle*) override {
threads_--;
}
void checkCalls() {
ASSERT_EQ(threads_, 0);
}
private:
std::atomic<int> threads_{0};
};
TEST(ThreadPoolExecutorTest, IOObserver) {
auto observer = std::make_shared<TestObserver>();
{
IOThreadPoolExecutor exe(10);
exe.addObserver(observer);
exe.setNumThreads(3);
exe.setNumThreads(0);
exe.setNumThreads(7);
exe.removeObserver(observer);
exe.setNumThreads(10);
}
observer->checkCalls();
}
TEST(ThreadPoolExecutorTest, CPUObserver) {
auto observer = std::make_shared<TestObserver>();
{
CPUThreadPoolExecutor exe(10);
exe.addObserver(observer);
exe.setNumThreads(3);
exe.setNumThreads(0);
exe.setNumThreads(7);
exe.removeObserver(observer);
exe.setNumThreads(10);
}
observer->checkCalls();
}
TEST(ThreadPoolExecutorTest, AddWithPriority) {
std::atomic_int c{0};
auto f = [&] { c++; };
// IO exe doesn't support priorities
IOThreadPoolExecutor ioExe(10);
EXPECT_THROW(ioExe.addWithPriority(f, 0), std::runtime_error);
CPUThreadPoolExecutor cpuExe(10, 3);
cpuExe.addWithPriority(f, -1);
cpuExe.addWithPriority(f, 0);
cpuExe.addWithPriority(f, 1);
cpuExe.addWithPriority(f, -2); // will add at the lowest priority
cpuExe.addWithPriority(f, 2); // will add at the highest priority
cpuExe.addWithPriority(f, Executor::LO_PRI);
cpuExe.addWithPriority(f, Executor::HI_PRI);
cpuExe.join();
EXPECT_EQ(7, c);
}
TEST(ThreadPoolExecutorTest, BlockingQueue) {
std::atomic_int c{0};
auto f = [&] {
burnMs(1)();
c++;
};
const int kQueueCapacity = 1;
const int kThreads = 1;
auto queue = std::make_unique<LifoSemMPMCQueue<
CPUThreadPoolExecutor::CPUTask,
QueueBehaviorIfFull::BLOCK>>(kQueueCapacity);
CPUThreadPoolExecutor cpuExe(
kThreads,
std::move(queue),
std::make_shared<NamedThreadFactory>("CPUThreadPool"));
// Add `f` five times. It sleeps for 1ms every time. Calling
// `cppExec.add()` is *almost* guaranteed to block because there's
// only 1 cpu worker thread.
for (int i = 0; i < 5; i++) {
EXPECT_NO_THROW(cpuExe.add(f));
}
cpuExe.join();
EXPECT_EQ(5, c);
}
TEST(PriorityThreadFactoryTest, ThreadPriority) {
errno = 0;
auto currentPriority = getpriority(PRIO_PROCESS, 0);
if (errno != 0) {
throwSystemError("failed to get current priority");
}
// Non-root users can only increase the priority value. Make sure we are
// trying to go to a higher priority than we are currently running as, up to
// the maximum allowed of 20.
int desiredPriority = std::min(20, currentPriority + 1);
PriorityThreadFactory factory(
std::make_shared<NamedThreadFactory>("stuff"), desiredPriority);
int actualPriority = -21;
factory.newThread([&]() { actualPriority = getpriority(PRIO_PROCESS, 0); })
.join();
EXPECT_EQ(desiredPriority, actualPriority);
}
class TestData : public folly::RequestData {
public:
explicit TestData(int data) : data_(data) {}
~TestData() override {}
bool hasCallback() override {
return false;
}
int data_;
};
TEST(ThreadPoolExecutorTest, RequestContext) {
CPUThreadPoolExecutor executor(1);
RequestContextScopeGuard rctx; // create new request context for this scope
EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
RequestContext::get()->setContextData("test", std::make_unique<TestData>(42));
auto data = RequestContext::get()->getContextData("test");
EXPECT_EQ(42, dynamic_cast<TestData*>(data)->data_);
executor.add([] {
auto data = RequestContext::get()->getContextData("test");
ASSERT_TRUE(data != nullptr);
EXPECT_EQ(42, dynamic_cast<TestData*>(data)->data_);
});
}
struct SlowMover {
explicit SlowMover(bool slow = false) : slow(slow) {}
SlowMover(SlowMover&& other) noexcept {
*this = std::move(other);
}
SlowMover& operator=(SlowMover&& other) noexcept {
slow = other.slow;
if (slow) {
/* sleep override */ std::this_thread::sleep_for(milliseconds(50));
}
return *this;
}
bool slow;
};
template <typename Q>
void bugD3527722_test() {
// Test that the queue does not get stuck if writes are completed in
// order opposite to how they are initiated.
Q q(1024);
std::atomic<int> turn{};
std::thread consumer1([&] {
++turn;
q.take();
});
std::thread consumer2([&] {
++turn;
q.take();
});
std::thread producer1([&] {
++turn;
while (turn < 4) {
;
}
++turn;
q.add(SlowMover(true));
});
std::thread producer2([&] {
++turn;
while (turn < 5) {
;
}
q.add(SlowMover(false));
});
producer1.join();
producer2.join();
consumer1.join();
consumer2.join();
}
TEST(ThreadPoolExecutorTest, LifoSemMPMCQueueBugD3527722) {
bugD3527722_test<LifoSemMPMCQueue<SlowMover>>();
}
template <typename T>
struct UBQ : public UnboundedBlockingQueue<T> {
explicit UBQ(int) {}
};
TEST(ThreadPoolExecutorTest, UnboundedBlockingQueueBugD3527722) {
bugD3527722_test<UBQ<SlowMover>>();
}
template <typename TPE, typename ERR_T>
static void ShutdownTest() {
// test that adding a .then() after we have
// started shutting down does not deadlock
folly::Optional<folly::Future<int>> f;
{
TPE fe(1);
f = folly::makeFuture().via(&fe).then([]() { burnMs(100)(); }).then([]() {
return 77;
});
}
EXPECT_THROW(f->get(), ERR_T);
}
TEST(ThreadPoolExecutorTest, ShutdownTestIO) {
ShutdownTest<IOThreadPoolExecutor, std::runtime_error>();
}
TEST(ThreadPoolExecutorTest, ShutdownTestCPU) {
ShutdownTest<CPUThreadPoolExecutor, folly::FutureException>();
}
template <typename TPE>
static void removeThreadTest() {
// test that adding a .then() after we have removed some threads
// doesn't cause deadlock and they are executed on different threads
folly::Optional<folly::Future<int>> f;
std::thread::id id1, id2;
TPE fe(2);
f = folly::makeFuture()
.via(&fe)
.then([&id1]() {
burnMs(100)();
id1 = std::this_thread::get_id();
})
.then([&id2]() {
return 77;
id2 = std::this_thread::get_id();
});
fe.setNumThreads(1);
// future::then should be fulfilled because there is other thread available
EXPECT_EQ(77, f->get());
// two thread should be different because then part should be rescheduled to
// the other thread
EXPECT_NE(id1, id2);
}
TEST(ThreadPoolExecutorTest, RemoveThreadTestIO) {
removeThreadTest<IOThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, RemoveThreadTestCPU) {
removeThreadTest<CPUThreadPoolExecutor>();
}
template <typename TPE>
static void resizeThreadWhileExecutingTest() {
TPE tpe(10);
EXPECT_EQ(10, tpe.numThreads());
std::atomic<int> completed(0);
auto f = [&]() {
burnMs(10)();
completed++;
};
for (int i = 0; i < 1000; i++) {
tpe.add(f);
}
tpe.setNumThreads(8);
EXPECT_EQ(8, tpe.numThreads());
tpe.setNumThreads(5);
EXPECT_EQ(5, tpe.numThreads());
tpe.setNumThreads(15);
EXPECT_EQ(15, tpe.numThreads());
tpe.stop();
EXPECT_EQ(1000, completed);
}
TEST(ThreadPoolExecutorTest, resizeThreadWhileExecutingTestIO) {
resizeThreadWhileExecutingTest<IOThreadPoolExecutor>();
}
TEST(ThreadPoolExecutorTest, resizeThreadWhileExecutingTestCPU) {
resizeThreadWhileExecutingTest<CPUThreadPoolExecutor>();
}