blob: 01022e9823179576253e630e64cba95c26707695 [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
kwibergbfefb032016-05-01 14:53:46 -070011#include <memory>
12
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020013#include "rtc_base/asyncinvoker.h"
14#include "rtc_base/asyncudpsocket.h"
15#include "rtc_base/event.h"
16#include "rtc_base/gunit.h"
17#include "rtc_base/nullsocketserver.h"
18#include "rtc_base/physicalsocketserver.h"
19#include "rtc_base/sigslot.h"
20#include "rtc_base/socketaddress.h"
21#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
23#if defined(WEBRTC_WIN)
24#include <comdef.h> // NOLINT
25#endif
26
27using namespace rtc;
28
29// Generates a sequence of numbers (collaboratively).
30class TestGenerator {
31 public:
32 TestGenerator() : last(0), count(0) {}
33
34 int Next(int prev) {
35 int result = prev + last;
36 last = result;
37 count += 1;
38 return result;
39 }
40
41 int last;
42 int count;
43};
44
45struct TestMessage : public MessageData {
46 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047
48 int value;
49};
50
51// Receives on a socket and sends by posting messages.
52class SocketClient : public TestGenerator, public sigslot::has_slots<> {
53 public:
54 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
55 Thread* post_thread, MessageHandler* phandler)
56 : socket_(AsyncUDPSocket::Create(socket, addr)),
57 post_thread_(post_thread),
58 post_handler_(phandler) {
59 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
60 }
61
Steve Anton9de3aac2017-10-24 10:08:26 -070062 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
64 SocketAddress address() const { return socket_->GetLocalAddress(); }
65
66 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
67 const SocketAddress& remote_addr,
68 const PacketTime& packet_time) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020069 EXPECT_EQ(size, sizeof(uint32_t));
70 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
71 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070073 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
74 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075 }
76
77 private:
78 AsyncUDPSocket* socket_;
79 Thread* post_thread_;
80 MessageHandler* post_handler_;
81};
82
83// Receives messages and sends on a socket.
84class MessageClient : public MessageHandler, public TestGenerator {
85 public:
86 MessageClient(Thread* pth, Socket* socket)
87 : socket_(socket) {
88 }
89
Steve Anton9de3aac2017-10-24 10:08:26 -070090 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091
Steve Anton9de3aac2017-10-24 10:08:26 -070092 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
94 int result = Next(msg->value);
95 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
96 delete msg;
97 }
98
99 private:
100 Socket* socket_;
101};
102
deadbeefaea92932017-05-23 12:55:03 -0700103class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 public:
tommie7251592017-07-14 14:44:46 -0700105 CustomThread()
106 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700107 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000109
110 bool WrapCurrent() {
111 return Thread::WrapCurrent();
112 }
113 void UnwrapCurrent() {
114 Thread::UnwrapCurrent();
115 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116};
117
118
119// A thread that does nothing when it runs and signals an event
120// when it is destroyed.
121class SignalWhenDestroyedThread : public Thread {
122 public:
123 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700124 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
125 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126
Steve Anton9de3aac2017-10-24 10:08:26 -0700127 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128 Stop();
129 event_->Set();
130 }
131
Steve Anton9de3aac2017-10-24 10:08:26 -0700132 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 // Do nothing.
134 }
135
136 private:
137 Event* event_;
138};
139
nissed9b75be2015-11-16 00:54:07 -0800140// A bool wrapped in a mutex, to avoid data races. Using a volatile
141// bool should be sufficient for correct code ("eventual consistency"
142// between caches is sufficient), but we can't tell the compiler about
143// that, and then tsan complains about a data race.
144
145// See also discussion at
146// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
147
148// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
149// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700150// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800151// performance critical, use a plain critical section for the time
152// being.
153
154class AtomicBool {
155 public:
156 explicit AtomicBool(bool value = false) : flag_(value) {}
157 AtomicBool& operator=(bool value) {
158 CritScope scoped_lock(&cs_);
159 flag_ = value;
160 return *this;
161 }
162 bool get() const {
163 CritScope scoped_lock(&cs_);
164 return flag_;
165 }
166
167 private:
pbos5ad935c2016-01-25 03:52:44 -0800168 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800169 bool flag_;
170};
171
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172// Function objects to test Thread::Invoke.
173struct FunctorA {
174 int operator()() { return 42; }
175};
176class FunctorB {
177 public:
nissed9b75be2015-11-16 00:54:07 -0800178 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 void operator()() { if (flag_) *flag_ = true; }
180 private:
nissed9b75be2015-11-16 00:54:07 -0800181 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182};
183struct FunctorC {
184 int operator()() {
185 Thread::Current()->ProcessMessages(50);
186 return 24;
187 }
188};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700189struct FunctorD {
190 public:
191 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
192 FunctorD(FunctorD&&) = default;
193 FunctorD& operator=(FunctorD&&) = default;
194 void operator()() { if (flag_) *flag_ = true; }
195 private:
196 AtomicBool* flag_;
197 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
198};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
200// See: https://code.google.com/p/webrtc/issues/detail?id=2409
201TEST(ThreadTest, DISABLED_Main) {
202 const SocketAddress addr("127.0.0.1", 0);
203
204 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700205 auto th1 = Thread::CreateWithSocketServer();
206 Socket* socket =
207 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
208 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000209
210 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700211 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700213 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
214 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215
216 socket->Connect(sock_client.address());
217
tommie7251592017-07-14 14:44:46 -0700218 th1->Start();
219 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
221 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700222 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223
224 // Give the clients a little while to run.
225 // Messages will be processed at 100, 300, 500, 700, 900.
226 Thread* th_main = Thread::Current();
227 th_main->ProcessMessages(1000);
228
229 // Stop the sending client. Give the receiver a bit longer to run, in case
230 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700231 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700233 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234
235 // Make sure the results were correct
236 EXPECT_EQ(5, msg_client.count);
237 EXPECT_EQ(34, msg_client.last);
238 EXPECT_EQ(5, sock_client.count);
239 EXPECT_EQ(55, sock_client.last);
240}
241
242// Test that setting thread names doesn't cause a malfunction.
243// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000244TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245 // Default name
tommie7251592017-07-14 14:44:46 -0700246 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 EXPECT_TRUE(thread->Start());
248 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700250 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800251 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252 EXPECT_TRUE(thread->Start());
253 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 // Really long name
tommie7251592017-07-14 14:44:46 -0700255 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
257 EXPECT_TRUE(thread->Start());
258 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259}
260
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000261TEST(ThreadTest, Wrap) {
262 Thread* current_thread = Thread::Current();
263 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 CustomThread* cthread = new CustomThread();
265 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000266 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 EXPECT_FALSE(cthread->IsOwned());
268 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000269 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000271 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272}
273
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000274TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700276 auto thread = Thread::CreateWithSocketServer();
277 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700279 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800280 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700282 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800283 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284 // Try calling bare functions.
285 struct LocalFuncs {
286 static int Func1() { return 999; }
287 static void Func2() {}
288 };
tommie7251592017-07-14 14:44:46 -0700289 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
290 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291}
292
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000293// Verifies that two threads calling Invoke on each other at the same time does
294// not deadlock.
295TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
296 AutoThread thread;
297 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800298 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000299
tommie7251592017-07-14 14:44:46 -0700300 auto other_thread = Thread::CreateWithSocketServer();
301 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000302
303 struct LocalFuncs {
304 static void Set(bool* out) { *out = true; }
305 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700306 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000307 }
308 };
309
310 bool called = false;
tommie7251592017-07-14 14:44:46 -0700311 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700312 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000313
314 EXPECT_TRUE(called);
315}
316
317// Verifies that if thread A invokes a call on thread B and thread C is trying
318// to invoke A at the same time, thread A does not handle C's invoke while
319// invoking B.
320TEST(ThreadTest, ThreeThreadsInvoke) {
321 AutoThread thread;
322 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700323 auto thread_b = Thread::CreateWithSocketServer();
324 auto thread_c = Thread::CreateWithSocketServer();
325 thread_b->Start();
326 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000327
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000328 class LockedBool {
329 public:
330 explicit LockedBool(bool value) : value_(value) {}
331
332 void Set(bool value) {
333 CritScope lock(&crit_);
334 value_ = value;
335 }
336
337 bool Get() {
338 CritScope lock(&crit_);
339 return value_;
340 }
341
342 private:
343 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700344 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000345 };
346
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000347 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000348 static void Set(LockedBool* out) { out->Set(true); }
349 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700350 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000351 }
352
353 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000354 static void SetAndInvokeSet(LockedBool* out,
355 Thread* thread,
356 LockedBool* out_inner) {
357 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000358 InvokeSet(thread, out_inner);
359 }
360
361 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
362 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800363 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
364 Thread* thread1,
365 Thread* thread2,
366 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000367 CriticalSection crit;
368 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000369
deadbeef162cb532017-02-23 17:10:07 -0800370 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700371 RTC_FROM_HERE, thread1,
372 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000373
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000374 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000375 }
376 };
377
deadbeef162cb532017-02-23 17:10:07 -0800378 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000379 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000380
381 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
382 // Thread B returns when C receives the call and C should be blocked until A
383 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700384 thread_b->Invoke<void>(RTC_FROM_HERE,
385 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
386 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000387 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000388
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000389 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000390}
391
jbauch25d1f282016-02-05 00:25:02 -0800392// Set the name on a thread when the underlying QueueDestroyed signal is
393// triggered. This causes an error if the object is already partially
394// destroyed.
395class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
396 public:
397 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
398 thread->SignalQueueDestroyed.connect(
399 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
400 }
401
402 void OnQueueDestroyed() {
403 // Makes sure that if we access the Thread while it's being destroyed, that
404 // it doesn't cause a problem because the vtable has been modified.
405 thread_->SetName("foo", nullptr);
406 }
407
408 private:
409 Thread* thread_;
410};
411
412TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700413 auto thread1 = Thread::CreateWithSocketServer();
414 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
415 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800416
417 Thread* thread2 = new AutoThread();
418 SetNameOnSignalQueueDestroyedTester tester2(thread2);
419 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800420}
421
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422class AsyncInvokeTest : public testing::Test {
423 public:
424 void IntCallback(int value) {
425 EXPECT_EQ(expected_thread_, Thread::Current());
426 int_value_ = value;
427 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428 void SetExpectedThreadForIntCallback(Thread* thread) {
429 expected_thread_ = thread;
430 }
431
432 protected:
433 enum { kWaitTimeout = 1000 };
434 AsyncInvokeTest()
435 : int_value_(0),
deadbeef37f5ecf2017-02-27 14:06:41 -0800436 expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437
438 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 Thread* expected_thread_;
440};
441
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000442TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443 AsyncInvoker invoker;
444 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700445 auto thread = Thread::CreateWithSocketServer();
446 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800448 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700449 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800450 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700451 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452}
453
Cameron Pickettd132ce12018-03-12 16:07:37 -0700454TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
455 AsyncInvoker invoker;
456 // Create and start the thread.
457 auto thread = Thread::CreateWithSocketServer();
458 thread->Start();
459 // Try calling functor.
460 AtomicBool called;
461 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
462 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
463 thread->Stop();
464}
465
deadbeef162cb532017-02-23 17:10:07 -0800466TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
467 // Use these events to get in a state where the functor is in the middle of
468 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
469 // is run.
470 Event functor_started(false, false);
deadbeefaea92932017-05-23 12:55:03 -0700471 Event functor_continue(false, false);
deadbeef162cb532017-02-23 17:10:07 -0800472 Event functor_finished(false, false);
473
tommie7251592017-07-14 14:44:46 -0700474 auto thread = Thread::CreateWithSocketServer();
475 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800476 volatile bool invoker_destroyed = false;
477 {
deadbeef3af63b02017-08-08 17:59:47 -0700478 auto functor = [&functor_started, &functor_continue, &functor_finished,
479 &invoker_destroyed] {
480 functor_started.Set();
481 functor_continue.Wait(Event::kForever);
482 rtc::Thread::Current()->SleepMs(kWaitTimeout);
483 EXPECT_FALSE(invoker_destroyed);
484 functor_finished.Set();
485 };
deadbeef162cb532017-02-23 17:10:07 -0800486 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700487 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800488 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700489
deadbeef3af63b02017-08-08 17:59:47 -0700490 // Destroy the invoker while the functor is still executing (doing
491 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700492 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800493 }
494
495 // If the destructor DIDN'T wait for the functor to finish executing, it will
496 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
497 // second.
498 invoker_destroyed = true;
499 functor_finished.Wait(Event::kForever);
500}
501
deadbeef3af63b02017-08-08 17:59:47 -0700502// Variant of the above test where the async-invoked task calls AsyncInvoke
503// *again*, for the thread on which the AsyncInvoker is currently being
504// destroyed. This shouldn't deadlock or crash; this second invocation should
505// just be ignored.
506TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
507 Event functor_started(false, false);
508 // Flag used to verify that the recursively invoked task never actually runs.
509 bool reentrant_functor_run = false;
510
511 Thread* main = Thread::Current();
512 Thread thread;
513 thread.Start();
514 {
515 AsyncInvoker invoker;
516 auto reentrant_functor = [&reentrant_functor_run] {
517 reentrant_functor_run = true;
518 };
519 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
520 functor_started.Set();
521 Thread::Current()->SleepMs(kWaitTimeout);
522 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
523 };
524 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
525 // task on |main|. But this second queued task should never run, since the
526 // destructor will be entered before it's even invoked.
527 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
528 functor_started.Wait(Event::kForever);
529 }
530 EXPECT_FALSE(reentrant_functor_run);
531}
532
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000533TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800535 AtomicBool flag1;
536 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700538 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
539 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800541 EXPECT_FALSE(flag1.get());
542 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543 // Force them to run now.
544 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800545 EXPECT_TRUE(flag1.get());
546 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547}
548
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000549TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000550 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800551 AtomicBool flag1;
552 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000553 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700554 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700556 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800558 EXPECT_FALSE(flag1.get());
559 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000560 // Execute pending calls with id == 5.
561 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800562 EXPECT_TRUE(flag1.get());
563 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000564 flag1 = false;
565 // Execute all pending calls. The id == 5 call should not execute again.
566 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800567 EXPECT_FALSE(flag1.get());
568 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569}
570
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200571class GuardedAsyncInvokeTest : public testing::Test {
572 public:
573 void IntCallback(int value) {
574 EXPECT_EQ(expected_thread_, Thread::Current());
575 int_value_ = value;
576 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200577 void SetExpectedThreadForIntCallback(Thread* thread) {
578 expected_thread_ = thread;
579 }
580
581 protected:
582 const static int kWaitTimeout = 1000;
583 GuardedAsyncInvokeTest()
584 : int_value_(0),
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200585 expected_thread_(nullptr) {}
586
587 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200588 Thread* expected_thread_;
589};
590
591// Functor for creating an invoker.
592struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700593 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
594 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200595 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700596 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200597};
598
599// Test that we can call AsyncInvoke<void>() after the thread died.
600TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
601 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700602 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200603 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700604 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200605 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700606 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200607 // Kill |thread|.
608 thread = nullptr;
609 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800610 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700611 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200612 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800613 WAIT(called.get(), kWaitTimeout);
614 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200615}
616
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200617// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
618// when Thread is still alive.
619TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
620 GuardedAsyncInvoker invoker;
621 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800622 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700623 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800624 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200625}
626
Cameron Pickettd132ce12018-03-12 16:07:37 -0700627TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
628 GuardedAsyncInvoker invoker;
629 // Try calling functor.
630 AtomicBool called;
631 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
632 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
633}
634
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200635TEST_F(GuardedAsyncInvokeTest, Flush) {
636 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800637 AtomicBool flag1;
638 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200639 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700640 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
641 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200642 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800643 EXPECT_FALSE(flag1.get());
644 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200645 // Force them to run now.
646 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800647 EXPECT_TRUE(flag1.get());
648 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200649}
650
651TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
652 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800653 AtomicBool flag1;
654 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200655 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700656 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
657 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200658 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800659 EXPECT_FALSE(flag1.get());
660 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200661 // Execute pending calls with id == 5.
662 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800663 EXPECT_TRUE(flag1.get());
664 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200665 flag1 = false;
666 // Execute all pending calls. The id == 5 call should not execute again.
667 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800668 EXPECT_FALSE(flag1.get());
669 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200670}