blob: 2a24d6ca37ed7ca4ee64aa98bbe430c67bdf2634 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "rtc_base/thread.h"
12
kwibergbfefb032016-05-01 14:53:46 -070013#include <memory>
14
Danil Chapovalov912b3b82019-11-22 15:52:40 +010015#include "api/task_queue/task_queue_factory.h"
16#include "api/task_queue/task_queue_test.h"
Steve Anton10542f22019-01-11 09:11:00 -080017#include "rtc_base/async_invoker.h"
18#include "rtc_base/async_udp_socket.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010019#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/event.h"
21#include "rtc_base/gunit.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010022#include "rtc_base/internal/default_socket_server.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "rtc_base/null_socket_server.h"
24#include "rtc_base/physical_socket_server.h"
25#include "rtc_base/socket_address.h"
Markus Handell4ab7dde2020-07-10 13:23:25 +020026#include "rtc_base/synchronization/mutex.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010027#include "rtc_base/task_utils/to_queued_task.h"
Artem Titove41c4332018-07-25 15:04:28 +020028#include "rtc_base/third_party/sigslot/sigslot.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010029#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
31#if defined(WEBRTC_WIN)
32#include <comdef.h> // NOLINT
Markus Handell4ab7dde2020-07-10 13:23:25 +020033
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034#endif
35
Mirko Bonadeie10b1632018-12-11 18:43:40 +010036namespace rtc {
37namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038
Sebastian Jansson73387822020-01-16 11:15:35 +010039using ::webrtc::ToQueuedTask;
40
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041// Generates a sequence of numbers (collaboratively).
42class TestGenerator {
43 public:
44 TestGenerator() : last(0), count(0) {}
45
46 int Next(int prev) {
47 int result = prev + last;
48 last = result;
49 count += 1;
50 return result;
51 }
52
53 int last;
54 int count;
55};
56
57struct TestMessage : public MessageData {
58 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059
60 int value;
61};
62
63// Receives on a socket and sends by posting messages.
64class SocketClient : public TestGenerator, public sigslot::has_slots<> {
65 public:
Yves Gerey665174f2018-06-19 15:03:05 +020066 SocketClient(AsyncSocket* socket,
67 const SocketAddress& addr,
68 Thread* post_thread,
69 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070 : socket_(AsyncUDPSocket::Create(socket, addr)),
71 post_thread_(post_thread),
72 post_handler_(phandler) {
73 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
74 }
75
Steve Anton9de3aac2017-10-24 10:08:26 -070076 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077
78 SocketAddress address() const { return socket_->GetLocalAddress(); }
79
Yves Gerey665174f2018-06-19 15:03:05 +020080 void OnPacket(AsyncPacketSocket* socket,
81 const char* buf,
82 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010084 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020085 EXPECT_EQ(size, sizeof(uint32_t));
86 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
87 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070089 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
90 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091 }
92
93 private:
94 AsyncUDPSocket* socket_;
95 Thread* post_thread_;
96 MessageHandler* post_handler_;
97};
98
99// Receives messages and sends on a socket.
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200100class MessageClient : public MessageHandlerAutoCleanup, public TestGenerator {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000101 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200102 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103
Steve Anton9de3aac2017-10-24 10:08:26 -0700104 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105
Steve Anton9de3aac2017-10-24 10:08:26 -0700106 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
108 int result = Next(msg->value);
109 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
110 delete msg;
111 }
112
113 private:
114 Socket* socket_;
115};
116
deadbeefaea92932017-05-23 12:55:03 -0700117class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 public:
tommie7251592017-07-14 14:44:46 -0700119 CustomThread()
120 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700121 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000123
Yves Gerey665174f2018-06-19 15:03:05 +0200124 bool WrapCurrent() { return Thread::WrapCurrent(); }
125 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126};
127
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128// A thread that does nothing when it runs and signals an event
129// when it is destroyed.
130class SignalWhenDestroyedThread : public Thread {
131 public:
132 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700133 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
134 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135
Steve Anton9de3aac2017-10-24 10:08:26 -0700136 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 Stop();
138 event_->Set();
139 }
140
Steve Anton9de3aac2017-10-24 10:08:26 -0700141 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 // Do nothing.
143 }
144
145 private:
146 Event* event_;
147};
148
nissed9b75be2015-11-16 00:54:07 -0800149// A bool wrapped in a mutex, to avoid data races. Using a volatile
150// bool should be sufficient for correct code ("eventual consistency"
151// between caches is sufficient), but we can't tell the compiler about
152// that, and then tsan complains about a data race.
153
154// See also discussion at
155// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
156
157// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
158// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700159// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800160// performance critical, use a plain critical section for the time
161// being.
162
163class AtomicBool {
164 public:
165 explicit AtomicBool(bool value = false) : flag_(value) {}
166 AtomicBool& operator=(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200167 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800168 flag_ = value;
169 return *this;
170 }
171 bool get() const {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200172 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800173 return flag_;
174 }
175
176 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200177 mutable webrtc::Mutex mutex_;
nissed9b75be2015-11-16 00:54:07 -0800178 bool flag_;
179};
180
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181// Function objects to test Thread::Invoke.
182struct FunctorA {
183 int operator()() { return 42; }
184};
185class FunctorB {
186 public:
nissed9b75be2015-11-16 00:54:07 -0800187 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200188 void operator()() {
189 if (flag_)
190 *flag_ = true;
191 }
192
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193 private:
nissed9b75be2015-11-16 00:54:07 -0800194 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195};
196struct FunctorC {
197 int operator()() {
198 Thread::Current()->ProcessMessages(50);
199 return 24;
200 }
201};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700202struct FunctorD {
203 public:
204 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
205 FunctorD(FunctorD&&) = default;
206 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200207 void operator()() {
208 if (flag_)
209 *flag_ = true;
210 }
211
Cameron Pickettd132ce12018-03-12 16:07:37 -0700212 private:
213 AtomicBool* flag_;
214 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
215};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216
217// See: https://code.google.com/p/webrtc/issues/detail?id=2409
218TEST(ThreadTest, DISABLED_Main) {
219 const SocketAddress addr("127.0.0.1", 0);
220
221 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700222 auto th1 = Thread::CreateWithSocketServer();
223 Socket* socket =
224 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
225 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226
227 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700228 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700230 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
231 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232
233 socket->Connect(sock_client.address());
234
tommie7251592017-07-14 14:44:46 -0700235 th1->Start();
236 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700239 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
241 // Give the clients a little while to run.
242 // Messages will be processed at 100, 300, 500, 700, 900.
243 Thread* th_main = Thread::Current();
244 th_main->ProcessMessages(1000);
245
246 // Stop the sending client. Give the receiver a bit longer to run, in case
247 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700248 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700250 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251
252 // Make sure the results were correct
253 EXPECT_EQ(5, msg_client.count);
254 EXPECT_EQ(34, msg_client.last);
255 EXPECT_EQ(5, sock_client.count);
256 EXPECT_EQ(55, sock_client.last);
257}
258
Tommife041642021-04-07 10:08:28 +0200259TEST(ThreadTest, CountBlockingCalls) {
260 // When the test runs, this will print out:
261 // (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
262 RTC_LOG_THREAD_BLOCK_COUNT();
263#if RTC_DCHECK_IS_ON
264 rtc::Thread* current = rtc::Thread::Current();
265 ASSERT_TRUE(current);
266 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
267 [&](uint32_t actual_block, uint32_t could_block) {
268 EXPECT_EQ(1u, actual_block);
269 EXPECT_EQ(1u, could_block);
270 });
271
272 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
273 EXPECT_EQ(0u, blocked_calls.GetCouldBeBlockingCallCount());
274 EXPECT_EQ(0u, blocked_calls.GetTotalBlockedCallCount());
275
276 // Test invoking on the current thread. This should not count as an 'actual'
277 // invoke, but should still count as an invoke that could block since we
278 // that the call to Invoke serves a purpose in some configurations (and should
279 // not be used a general way to call methods on the same thread).
280 current->Invoke<void>(RTC_FROM_HERE, []() {});
281 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
282 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
283 EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
284
285 // Create a new thread to invoke on.
286 auto thread = Thread::CreateWithSocketServer();
287 thread->Start();
288 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, []() { return 42; }));
289 EXPECT_EQ(1u, blocked_calls.GetBlockingCallCount());
290 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
291 EXPECT_EQ(2u, blocked_calls.GetTotalBlockedCallCount());
292 thread->Stop();
293 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2);
294#else
295 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
296 RTC_LOG(LS_INFO) << "Test not active in this config";
297#endif
298}
299
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200300#if RTC_DCHECK_IS_ON
301TEST(ThreadTest, CountBlockingCallsOneCallback) {
302 rtc::Thread* current = rtc::Thread::Current();
303 ASSERT_TRUE(current);
304 bool was_called_back = false;
305 {
306 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
307 [&](uint32_t actual_block, uint32_t could_block) {
308 was_called_back = true;
309 });
310 current->Invoke<void>(RTC_FROM_HERE, []() {});
311 }
312 EXPECT_TRUE(was_called_back);
313}
314
315TEST(ThreadTest, CountBlockingCallsSkipCallback) {
316 rtc::Thread* current = rtc::Thread::Current();
317 ASSERT_TRUE(current);
318 bool was_called_back = false;
319 {
320 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
321 [&](uint32_t actual_block, uint32_t could_block) {
322 was_called_back = true;
323 });
324 // Changed `blocked_calls` to not issue the callback if there are 1 or
325 // fewer blocking calls (i.e. we set the minimum required number to 2).
326 blocked_calls.set_minimum_call_count_for_callback(2);
327 current->Invoke<void>(RTC_FROM_HERE, []() {});
328 }
329 // We should not have gotten a call back.
330 EXPECT_FALSE(was_called_back);
331}
332#endif
333
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334// Test that setting thread names doesn't cause a malfunction.
335// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000336TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337 // Default name
tommie7251592017-07-14 14:44:46 -0700338 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 EXPECT_TRUE(thread->Start());
340 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700342 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800343 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344 EXPECT_TRUE(thread->Start());
345 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346 // Really long name
tommie7251592017-07-14 14:44:46 -0700347 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
349 EXPECT_TRUE(thread->Start());
350 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351}
352
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000353TEST(ThreadTest, Wrap) {
354 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200355 ThreadManager::Instance()->SetCurrentThread(nullptr);
356
357 {
358 CustomThread cthread;
359 EXPECT_TRUE(cthread.WrapCurrent());
360 EXPECT_EQ(&cthread, Thread::Current());
361 EXPECT_TRUE(cthread.RunningForTest());
362 EXPECT_FALSE(cthread.IsOwned());
363 cthread.UnwrapCurrent();
364 EXPECT_FALSE(cthread.RunningForTest());
365 }
366 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367}
368
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200369#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
370TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
371 // Create and start the thread.
372 auto thread1 = Thread::CreateWithSocketServer();
373 auto thread2 = Thread::CreateWithSocketServer();
374
375 thread1->PostTask(ToQueuedTask(
376 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
377 Thread* th_main = Thread::Current();
378 th_main->ProcessMessages(100);
379}
380
381TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
382 // Create and start the thread.
383 auto thread1 = Thread::CreateWithSocketServer();
384 auto thread2 = Thread::CreateWithSocketServer();
385 auto thread3 = Thread::CreateWithSocketServer();
386 auto thread4 = Thread::CreateWithSocketServer();
387
388 thread1->AllowInvokesToThread(thread2.get());
389 thread1->AllowInvokesToThread(thread3.get());
390
391 thread1->PostTask(ToQueuedTask([&]() {
392 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
393 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
394 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
395 }));
396 Thread* th_main = Thread::Current();
397 th_main->ProcessMessages(100);
398}
399
400TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
401 // Create and start the thread.
402 auto thread1 = Thread::CreateWithSocketServer();
403 auto thread2 = Thread::CreateWithSocketServer();
404
405 thread1->DisallowAllInvokes();
406
407 thread1->PostTask(ToQueuedTask([&]() {
408 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
409 }));
410 Thread* th_main = Thread::Current();
411 th_main->ProcessMessages(100);
412}
413#endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
414
415TEST(ThreadTest, InvokesAllowedByDefault) {
416 // Create and start the thread.
417 auto thread1 = Thread::CreateWithSocketServer();
418 auto thread2 = Thread::CreateWithSocketServer();
419
420 thread1->PostTask(ToQueuedTask(
421 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
422 Thread* th_main = Thread::Current();
423 th_main->ProcessMessages(100);
424}
425
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000426TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700428 auto thread = Thread::CreateWithSocketServer();
429 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000430 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700431 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800432 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700434 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800435 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000436 // Try calling bare functions.
437 struct LocalFuncs {
438 static int Func1() { return 999; }
439 static void Func2() {}
440 };
tommie7251592017-07-14 14:44:46 -0700441 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
442 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443}
444
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000445// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100446// not deadlock but crash.
447#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
448TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
449 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000450 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100451 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700452 auto other_thread = Thread::CreateWithSocketServer();
453 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100454 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
455 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
456 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000457}
458
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100459TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
460 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
461 AutoThread thread;
462 Thread* first = Thread::Current();
463
464 auto second = Thread::Create();
465 second->Start();
466 auto third = Thread::Create();
467 third->Start();
468
469 second->Invoke<void>(RTC_FROM_HERE, [&] {
470 third->Invoke<void>(RTC_FROM_HERE, [&] {
471 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
472 });
473 });
474}
475
476#endif
477
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000478// Verifies that if thread A invokes a call on thread B and thread C is trying
479// to invoke A at the same time, thread A does not handle C's invoke while
480// invoking B.
481TEST(ThreadTest, ThreeThreadsInvoke) {
482 AutoThread thread;
483 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700484 auto thread_b = Thread::CreateWithSocketServer();
485 auto thread_c = Thread::CreateWithSocketServer();
486 thread_b->Start();
487 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000488
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000489 class LockedBool {
490 public:
491 explicit LockedBool(bool value) : value_(value) {}
492
493 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200494 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000495 value_ = value;
496 }
497
498 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200499 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000500 return value_;
501 }
502
503 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200504 webrtc::Mutex mutex_;
505 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000506 };
507
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000508 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000509 static void Set(LockedBool* out) { out->Set(true); }
510 static void InvokeSet(Thread* thread, LockedBool* out) {
Niels Möller1a29a5d2021-01-18 11:35:23 +0100511 thread->Invoke<void>(RTC_FROM_HERE, [out] { Set(out); });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000512 }
513
514 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000515 static void SetAndInvokeSet(LockedBool* out,
516 Thread* thread,
517 LockedBool* out_inner) {
518 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000519 InvokeSet(thread, out_inner);
520 }
521
522 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
523 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800524 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
525 Thread* thread1,
526 Thread* thread2,
527 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000528 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000529
deadbeef162cb532017-02-23 17:10:07 -0800530 invoker->AsyncInvoke<void>(
Niels Möller1a29a5d2021-01-18 11:35:23 +0100531 RTC_FROM_HERE, thread1, [&async_invoked, thread2, out] {
532 SetAndInvokeSet(&async_invoked, thread2, out);
533 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000534
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000535 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000536 }
537 };
538
deadbeef162cb532017-02-23 17:10:07 -0800539 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000540 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000541
542 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
543 // Thread B returns when C receives the call and C should be blocked until A
544 // starts to process messages.
Niels Möller1a29a5d2021-01-18 11:35:23 +0100545 Thread* thread_c_ptr = thread_c.get();
546 thread_b->Invoke<void>(
547 RTC_FROM_HERE, [&invoker, thread_c_ptr, thread_a, &thread_a_called] {
548 LocalFuncs::AsyncInvokeSetAndWait(&invoker, thread_c_ptr, thread_a,
549 &thread_a_called);
550 });
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000551 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000552
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000553 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000554}
555
jbauch25d1f282016-02-05 00:25:02 -0800556// Set the name on a thread when the underlying QueueDestroyed signal is
557// triggered. This causes an error if the object is already partially
558// destroyed.
559class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
560 public:
561 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
562 thread->SignalQueueDestroyed.connect(
563 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
564 }
565
566 void OnQueueDestroyed() {
567 // Makes sure that if we access the Thread while it's being destroyed, that
568 // it doesn't cause a problem because the vtable has been modified.
569 thread_->SetName("foo", nullptr);
570 }
571
572 private:
573 Thread* thread_;
574};
575
576TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700577 auto thread1 = Thread::CreateWithSocketServer();
578 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
579 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800580
581 Thread* thread2 = new AutoThread();
582 SetNameOnSignalQueueDestroyedTester tester2(thread2);
583 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800584}
585
Sebastian Jansson73387822020-01-16 11:15:35 +0100586class ThreadQueueTest : public ::testing::Test, public Thread {
587 public:
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100588 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {}
Sebastian Jansson73387822020-01-16 11:15:35 +0100589 bool IsLocked_Worker() {
590 if (!CritForTest()->TryEnter()) {
591 return true;
592 }
593 CritForTest()->Leave();
594 return false;
595 }
596 bool IsLocked() {
597 // We have to do this on a worker thread, or else the TryEnter will
598 // succeed, since our critical sections are reentrant.
599 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
600 worker->Start();
Niels Möller1a29a5d2021-01-18 11:35:23 +0100601 return worker->Invoke<bool>(RTC_FROM_HERE,
602 [this] { return IsLocked_Worker(); });
Sebastian Jansson73387822020-01-16 11:15:35 +0100603 }
604};
605
606struct DeletedLockChecker {
607 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
608 : test(test), was_locked(was_locked), deleted(deleted) {}
609 ~DeletedLockChecker() {
610 *deleted = true;
611 *was_locked = test->IsLocked();
612 }
613 ThreadQueueTest* test;
614 bool* was_locked;
615 bool* deleted;
616};
617
618static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
619 EXPECT_TRUE(q != nullptr);
620 int64_t now = TimeMillis();
621 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
622 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
623 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
624 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
625 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
626
627 Message msg;
628 for (size_t i = 0; i < 5; ++i) {
629 memset(&msg, 0, sizeof(msg));
630 EXPECT_TRUE(q->Get(&msg, 0));
631 EXPECT_EQ(i, msg.message_id);
632 }
633
634 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
635}
636
637TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100638 Thread q(CreateDefaultSocketServer(), true);
Sebastian Jansson73387822020-01-16 11:15:35 +0100639 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
640
641 NullSocketServer nullss;
642 Thread q_nullss(&nullss, true);
643 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
644}
645
646TEST_F(ThreadQueueTest, DisposeNotLocked) {
647 bool was_locked = true;
648 bool deleted = false;
649 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
650 Dispose(d);
651 Message msg;
652 EXPECT_FALSE(Get(&msg, 0));
653 EXPECT_TRUE(deleted);
654 EXPECT_FALSE(was_locked);
655}
656
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200657class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100658 public:
659 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
660 ~DeletedMessageHandler() override { *deleted_ = true; }
661 void OnMessage(Message* msg) override {}
662
663 private:
664 bool* deleted_;
665};
666
667TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
668 bool deleted = false;
669 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
670 // First, post a dispose.
671 Dispose(handler);
672 // Now, post a message, which should *not* be returned by Get().
673 Post(RTC_FROM_HERE, handler, 1);
674 Message msg;
675 EXPECT_FALSE(Get(&msg, 0));
676 EXPECT_TRUE(deleted);
677}
678
679// Ensure that ProcessAllMessageQueues does its essential function; process
680// all messages (both delayed and non delayed) up until the current time, on
681// all registered message queues.
682TEST(ThreadManager, ProcessAllMessageQueues) {
683 Event entered_process_all_message_queues(true, false);
684 auto a = Thread::CreateWithSocketServer();
685 auto b = Thread::CreateWithSocketServer();
686 a->Start();
687 b->Start();
688
689 volatile int messages_processed = 0;
690 auto incrementer = [&messages_processed,
691 &entered_process_all_message_queues] {
692 // Wait for event as a means to ensure Increment doesn't occur outside
693 // of ProcessAllMessageQueues. The event is set by a message posted to
694 // the main thread, which is guaranteed to be handled inside
695 // ProcessAllMessageQueues.
696 entered_process_all_message_queues.Wait(Event::kForever);
697 AtomicOps::Increment(&messages_processed);
698 };
699 auto event_signaler = [&entered_process_all_message_queues] {
700 entered_process_all_message_queues.Set();
701 };
702
703 // Post messages (both delayed and non delayed) to both threads.
704 a->PostTask(ToQueuedTask(incrementer));
705 b->PostTask(ToQueuedTask(incrementer));
706 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
707 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
708 rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
709
710 ThreadManager::ProcessAllMessageQueuesForTesting();
711 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
712}
713
714// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
715TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
716 auto t = Thread::CreateWithSocketServer();
717 t->Start();
718 t->Quit();
719 ThreadManager::ProcessAllMessageQueuesForTesting();
720}
721
722// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
723// messages.
724TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
725 Event entered_process_all_message_queues(true, false);
726 auto t = Thread::CreateWithSocketServer();
727 t->Start();
728
729 auto clearer = [&entered_process_all_message_queues] {
730 // Wait for event as a means to ensure Clear doesn't occur outside of
731 // ProcessAllMessageQueues. The event is set by a message posted to the
732 // main thread, which is guaranteed to be handled inside
733 // ProcessAllMessageQueues.
734 entered_process_all_message_queues.Wait(Event::kForever);
735 rtc::Thread::Current()->Clear(nullptr);
736 };
737 auto event_signaler = [&entered_process_all_message_queues] {
738 entered_process_all_message_queues.Set();
739 };
740
741 // Post messages (both delayed and non delayed) to both threads.
742 t->PostTask(RTC_FROM_HERE, clearer);
743 rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
744 ThreadManager::ProcessAllMessageQueuesForTesting();
745}
746
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200747class RefCountedHandler : public MessageHandlerAutoCleanup,
748 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100749 public:
750 void OnMessage(Message* msg) override {}
751};
752
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200753class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100754 public:
755 void OnMessage(Message* msg) override {}
756};
757
758TEST(ThreadManager, ClearReentrant) {
759 std::unique_ptr<Thread> t(Thread::Create());
760 EmptyHandler handler;
761 RefCountedHandler* inner_handler(
762 new rtc::RefCountedObject<RefCountedHandler>());
763 // When the empty handler is destroyed, it will clear messages queued for
764 // itself. The message to be cleared itself wraps a MessageHandler object
765 // (RefCountedHandler) so this will cause the message queue to be cleared
766 // again in a re-entrant fashion, which previously triggered a DCHECK.
767 // The inner handler will be removed in a re-entrant fashion from the
768 // message queue of the thread while the outer handler is removed, verifying
769 // that the iterator is not invalidated in "MessageQueue::Clear".
770 t->Post(RTC_FROM_HERE, inner_handler, 0);
771 t->Post(RTC_FROM_HERE, &handler, 0,
772 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
773}
774
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200775class AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776 public:
777 void IntCallback(int value) {
778 EXPECT_EQ(expected_thread_, Thread::Current());
779 int_value_ = value;
780 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781 void SetExpectedThreadForIntCallback(Thread* thread) {
782 expected_thread_ = thread;
783 }
784
785 protected:
786 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200787 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000788
789 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000790 Thread* expected_thread_;
791};
792
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000793TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000794 AsyncInvoker invoker;
795 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700796 auto thread = Thread::CreateWithSocketServer();
797 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800799 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700800 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800801 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700802 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000803}
804
Cameron Pickettd132ce12018-03-12 16:07:37 -0700805TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
806 AsyncInvoker invoker;
807 // Create and start the thread.
808 auto thread = Thread::CreateWithSocketServer();
809 thread->Start();
810 // Try calling functor.
811 AtomicBool called;
812 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
813 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
814 thread->Stop();
815}
816
deadbeef162cb532017-02-23 17:10:07 -0800817TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
818 // Use these events to get in a state where the functor is in the middle of
819 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
820 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100821 Event functor_started;
822 Event functor_continue;
823 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800824
tommie7251592017-07-14 14:44:46 -0700825 auto thread = Thread::CreateWithSocketServer();
826 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800827 volatile bool invoker_destroyed = false;
828 {
deadbeef3af63b02017-08-08 17:59:47 -0700829 auto functor = [&functor_started, &functor_continue, &functor_finished,
830 &invoker_destroyed] {
831 functor_started.Set();
832 functor_continue.Wait(Event::kForever);
833 rtc::Thread::Current()->SleepMs(kWaitTimeout);
834 EXPECT_FALSE(invoker_destroyed);
835 functor_finished.Set();
836 };
deadbeef162cb532017-02-23 17:10:07 -0800837 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700838 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800839 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700840
deadbeef3af63b02017-08-08 17:59:47 -0700841 // Destroy the invoker while the functor is still executing (doing
842 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700843 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800844 }
845
846 // If the destructor DIDN'T wait for the functor to finish executing, it will
847 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
848 // second.
849 invoker_destroyed = true;
850 functor_finished.Wait(Event::kForever);
851}
852
deadbeef3af63b02017-08-08 17:59:47 -0700853// Variant of the above test where the async-invoked task calls AsyncInvoke
854// *again*, for the thread on which the AsyncInvoker is currently being
855// destroyed. This shouldn't deadlock or crash; this second invocation should
856// just be ignored.
857TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100858 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700859 // Flag used to verify that the recursively invoked task never actually runs.
860 bool reentrant_functor_run = false;
861
862 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200863 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700864 thread.Start();
865 {
866 AsyncInvoker invoker;
867 auto reentrant_functor = [&reentrant_functor_run] {
868 reentrant_functor_run = true;
869 };
870 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
871 functor_started.Set();
872 Thread::Current()->SleepMs(kWaitTimeout);
873 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
874 };
875 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
876 // task on |main|. But this second queued task should never run, since the
877 // destructor will be entered before it's even invoked.
878 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
879 functor_started.Wait(Event::kForever);
880 }
881 EXPECT_FALSE(reentrant_functor_run);
882}
883
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000884TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000885 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800886 AtomicBool flag1;
887 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700889 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
890 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000891 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800892 EXPECT_FALSE(flag1.get());
893 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894 // Force them to run now.
895 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800896 EXPECT_TRUE(flag1.get());
897 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000898}
899
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000900TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800902 AtomicBool flag1;
903 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000904 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700905 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000906 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700907 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800909 EXPECT_FALSE(flag1.get());
910 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000911 // Execute pending calls with id == 5.
912 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800913 EXPECT_TRUE(flag1.get());
914 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 flag1 = false;
916 // Execute all pending calls. The id == 5 call should not execute again.
917 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800918 EXPECT_FALSE(flag1.get());
919 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920}
921
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100922void WaitAndSetEvent(Event* wait_event, Event* set_event) {
923 wait_event->Wait(Event::kForever);
924 set_event->Set();
925}
926
927// A functor that keeps track of the number of copies and moves.
928class LifeCycleFunctor {
929 public:
930 struct Stats {
931 size_t copy_count = 0;
932 size_t move_count = 0;
933 };
934
935 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
936 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
937 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
938
939 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
940 stats_ = other.stats_;
941 event_ = other.event_;
942 ++stats_->copy_count;
943 return *this;
944 }
945
946 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
947 stats_ = other.stats_;
948 event_ = other.event_;
949 ++stats_->move_count;
950 return *this;
951 }
952
953 void operator()() { event_->Set(); }
954
955 private:
956 Stats* stats_;
957 Event* event_;
958};
959
960// A functor that verifies the thread it was destroyed on.
961class DestructionFunctor {
962 public:
963 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
964 : thread_(thread),
965 thread_was_current_(thread_was_current),
966 event_(event) {}
967 ~DestructionFunctor() {
968 // Only signal the event if this was the functor that was invoked to avoid
969 // the event being signaled due to the destruction of temporary/moved
970 // versions of this object.
971 if (was_invoked_) {
972 *thread_was_current_ = thread_->IsCurrent();
973 event_->Set();
974 }
975 }
976
977 void operator()() { was_invoked_ = true; }
978
979 private:
980 Thread* thread_;
981 bool* thread_was_current_;
982 Event* event_;
983 bool was_invoked_ = false;
984};
985
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100986TEST(ThreadPostTaskTest, InvokesWithLambda) {
987 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
988 background_thread->Start();
989
990 Event event;
991 background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
992 event.Wait(Event::kForever);
993}
994
995TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
996 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
997 background_thread->Start();
998
999 LifeCycleFunctor::Stats stats;
1000 Event event;
1001 LifeCycleFunctor functor(&stats, &event);
1002 background_thread->PostTask(RTC_FROM_HERE, functor);
1003 event.Wait(Event::kForever);
1004
1005 EXPECT_EQ(1u, stats.copy_count);
1006 EXPECT_EQ(0u, stats.move_count);
1007}
1008
1009TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
1010 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1011 background_thread->Start();
1012
1013 LifeCycleFunctor::Stats stats;
1014 Event event;
1015 LifeCycleFunctor functor(&stats, &event);
1016 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
1017 event.Wait(Event::kForever);
1018
1019 EXPECT_EQ(0u, stats.copy_count);
1020 EXPECT_EQ(1u, stats.move_count);
1021}
1022
1023TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
1024 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1025 background_thread->Start();
1026
1027 LifeCycleFunctor::Stats stats;
1028 Event event;
1029 LifeCycleFunctor functor(&stats, &event);
1030 LifeCycleFunctor& functor_ref = functor;
1031 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1032 event.Wait(Event::kForever);
1033
1034 EXPECT_EQ(1u, stats.copy_count);
1035 EXPECT_EQ(0u, stats.move_count);
1036}
1037
1038TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
1039 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1040 background_thread->Start();
1041
1042 Event event;
1043 bool was_invoked_on_background_thread = false;
1044 DestructionFunctor functor(background_thread.get(),
1045 &was_invoked_on_background_thread, &event);
1046 background_thread->PostTask(RTC_FROM_HERE, functor);
1047 event.Wait(Event::kForever);
1048
1049 EXPECT_TRUE(was_invoked_on_background_thread);
1050}
1051
1052TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
1053 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1054 background_thread->Start();
1055
1056 Event event;
1057 bool was_invoked_on_background_thread = false;
1058 DestructionFunctor functor(background_thread.get(),
1059 &was_invoked_on_background_thread, &event);
1060 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
1061 event.Wait(Event::kForever);
1062
1063 EXPECT_TRUE(was_invoked_on_background_thread);
1064}
1065
1066TEST(ThreadPostTaskTest,
1067 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1068 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1069 background_thread->Start();
1070
1071 Event event;
1072 bool was_invoked_on_background_thread = false;
1073 DestructionFunctor functor(background_thread.get(),
1074 &was_invoked_on_background_thread, &event);
1075 DestructionFunctor& functor_ref = functor;
1076 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1077 event.Wait(Event::kForever);
1078
1079 EXPECT_TRUE(was_invoked_on_background_thread);
1080}
1081
1082TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1083 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1084 background_thread->Start();
1085
1086 Event event;
1087 bool was_invoked_on_background_thread = false;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001088 Thread* background_thread_ptr = background_thread.get();
1089 background_thread->PostTask(
1090 RTC_FROM_HERE,
1091 [background_thread_ptr, &was_invoked_on_background_thread, &event] {
1092 was_invoked_on_background_thread = background_thread_ptr->IsCurrent();
1093 event.Set();
1094 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001095 event.Wait(Event::kForever);
1096
1097 EXPECT_TRUE(was_invoked_on_background_thread);
1098}
1099
1100TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1101 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1102 background_thread->Start();
1103
1104 // The first event ensures that SendSingleMessage() is not blocking this
1105 // thread. The second event ensures that the message is processed.
1106 Event event_set_by_test_thread;
1107 Event event_set_by_background_thread;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001108 background_thread->PostTask(RTC_FROM_HERE, [&event_set_by_test_thread,
1109 &event_set_by_background_thread] {
1110 WaitAndSetEvent(&event_set_by_test_thread, &event_set_by_background_thread);
1111 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001112 event_set_by_test_thread.Set();
1113 event_set_by_background_thread.Wait(Event::kForever);
1114}
1115
1116TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1117 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1118 background_thread->Start();
1119
1120 Event first;
1121 Event second;
1122 Event third;
1123 Event fourth;
1124
Niels Möller1a29a5d2021-01-18 11:35:23 +01001125 background_thread->PostTask(
1126 RTC_FROM_HERE, [&first, &second] { WaitAndSetEvent(&first, &second); });
1127 background_thread->PostTask(
1128 RTC_FROM_HERE, [&second, &third] { WaitAndSetEvent(&second, &third); });
1129 background_thread->PostTask(
1130 RTC_FROM_HERE, [&third, &fourth] { WaitAndSetEvent(&third, &fourth); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001131
1132 // All tasks have been posted before the first one is unblocked.
1133 first.Set();
1134 // Only if the chain is invoked in posted order will the last event be set.
1135 fourth.Wait(Event::kForever);
1136}
1137
Steve Antonbcc1a762019-12-11 11:21:53 -08001138TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1139 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1140 background_thread->Start();
1141
1142 // The first event ensures that SendSingleMessage() is not blocking this
1143 // thread. The second event ensures that the message is processed.
1144 Event event_set_by_test_thread;
1145 Event event_set_by_background_thread;
1146 background_thread->PostDelayedTask(
1147 RTC_FROM_HERE,
Niels Möller1a29a5d2021-01-18 11:35:23 +01001148 [&event_set_by_test_thread, &event_set_by_background_thread] {
1149 WaitAndSetEvent(&event_set_by_test_thread,
1150 &event_set_by_background_thread);
1151 },
Steve Antonbcc1a762019-12-11 11:21:53 -08001152 /*milliseconds=*/10);
1153 event_set_by_test_thread.Set();
1154 event_set_by_background_thread.Wait(Event::kForever);
1155}
1156
1157TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001158 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001159 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1160 background_thread->Start();
1161
1162 Event first;
1163 Event second;
1164 Event third;
1165 Event fourth;
1166
Niels Möller1a29a5d2021-01-18 11:35:23 +01001167 background_thread->PostDelayedTask(
1168 RTC_FROM_HERE, [&third, &fourth] { WaitAndSetEvent(&third, &fourth); },
1169 /*milliseconds=*/11);
1170 background_thread->PostDelayedTask(
1171 RTC_FROM_HERE, [&first, &second] { WaitAndSetEvent(&first, &second); },
1172 /*milliseconds=*/9);
1173 background_thread->PostDelayedTask(
1174 RTC_FROM_HERE, [&second, &third] { WaitAndSetEvent(&second, &third); },
1175 /*milliseconds=*/10);
Steve Antonbcc1a762019-12-11 11:21:53 -08001176
1177 // All tasks have been posted before the first one is unblocked.
1178 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001179 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001180 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001181 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001182}
1183
Tommi6866dc72020-05-15 10:11:56 +02001184TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1185 auto current_tq = webrtc::TaskQueueBase::Current();
1186 {
1187 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1188 thread->WrapCurrent();
1189 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1190 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1191 thread->UnwrapCurrent();
1192 }
1193 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1194}
1195
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001196class ThreadFactory : public webrtc::TaskQueueFactory {
1197 public:
1198 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1199 CreateTaskQueue(absl::string_view /* name */,
1200 Priority /*priority*/) const override {
1201 std::unique_ptr<Thread> thread = Thread::Create();
1202 thread->Start();
1203 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1204 thread.release());
1205 }
1206};
1207
1208using ::webrtc::TaskQueueTest;
1209
1210INSTANTIATE_TEST_SUITE_P(RtcThread,
1211 TaskQueueTest,
1212 ::testing::Values(std::make_unique<ThreadFactory>));
1213
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001214} // namespace
1215} // namespace rtc