blob: d87c332ea29e9b9c6373270bb10b4facab2a7de3 [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
Steve Anton10542f22019-01-11 09:11:00 -080013#include "rtc_base/async_invoker.h"
14#include "rtc_base/async_udp_socket.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "rtc_base/event.h"
16#include "rtc_base/gunit.h"
Steve Anton10542f22019-01-11 09:11:00 -080017#include "rtc_base/null_socket_server.h"
18#include "rtc_base/physical_socket_server.h"
19#include "rtc_base/socket_address.h"
Artem Titove41c4332018-07-25 15:04:28 +020020#include "rtc_base/third_party/sigslot/sigslot.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#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
Mirko Bonadeie10b1632018-12-11 18:43:40 +010027namespace rtc {
28namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029
30// Generates a sequence of numbers (collaboratively).
31class TestGenerator {
32 public:
33 TestGenerator() : last(0), count(0) {}
34
35 int Next(int prev) {
36 int result = prev + last;
37 last = result;
38 count += 1;
39 return result;
40 }
41
42 int last;
43 int count;
44};
45
46struct TestMessage : public MessageData {
47 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048
49 int value;
50};
51
52// Receives on a socket and sends by posting messages.
53class SocketClient : public TestGenerator, public sigslot::has_slots<> {
54 public:
Yves Gerey665174f2018-06-19 15:03:05 +020055 SocketClient(AsyncSocket* socket,
56 const SocketAddress& addr,
57 Thread* post_thread,
58 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 : socket_(AsyncUDPSocket::Create(socket, addr)),
60 post_thread_(post_thread),
61 post_handler_(phandler) {
62 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
63 }
64
Steve Anton9de3aac2017-10-24 10:08:26 -070065 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066
67 SocketAddress address() const { return socket_->GetLocalAddress(); }
68
Yves Gerey665174f2018-06-19 15:03:05 +020069 void OnPacket(AsyncPacketSocket* socket,
70 const char* buf,
71 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010073 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020074 EXPECT_EQ(size, sizeof(uint32_t));
75 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
76 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070078 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
79 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080 }
81
82 private:
83 AsyncUDPSocket* socket_;
84 Thread* post_thread_;
85 MessageHandler* post_handler_;
86};
87
88// Receives messages and sends on a socket.
89class MessageClient : public MessageHandler, public TestGenerator {
90 public:
Yves Gerey665174f2018-06-19 15:03:05 +020091 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092
Steve Anton9de3aac2017-10-24 10:08:26 -070093 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094
Steve Anton9de3aac2017-10-24 10:08:26 -070095 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000096 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
97 int result = Next(msg->value);
98 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
99 delete msg;
100 }
101
102 private:
103 Socket* socket_;
104};
105
deadbeefaea92932017-05-23 12:55:03 -0700106class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107 public:
tommie7251592017-07-14 14:44:46 -0700108 CustomThread()
109 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700110 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000112
Yves Gerey665174f2018-06-19 15:03:05 +0200113 bool WrapCurrent() { return Thread::WrapCurrent(); }
114 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115};
116
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117// A thread that does nothing when it runs and signals an event
118// when it is destroyed.
119class SignalWhenDestroyedThread : public Thread {
120 public:
121 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700122 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
123 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124
Steve Anton9de3aac2017-10-24 10:08:26 -0700125 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 Stop();
127 event_->Set();
128 }
129
Steve Anton9de3aac2017-10-24 10:08:26 -0700130 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 // Do nothing.
132 }
133
134 private:
135 Event* event_;
136};
137
nissed9b75be2015-11-16 00:54:07 -0800138// A bool wrapped in a mutex, to avoid data races. Using a volatile
139// bool should be sufficient for correct code ("eventual consistency"
140// between caches is sufficient), but we can't tell the compiler about
141// that, and then tsan complains about a data race.
142
143// See also discussion at
144// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
145
146// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
147// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700148// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800149// performance critical, use a plain critical section for the time
150// being.
151
152class AtomicBool {
153 public:
154 explicit AtomicBool(bool value = false) : flag_(value) {}
155 AtomicBool& operator=(bool value) {
156 CritScope scoped_lock(&cs_);
157 flag_ = value;
158 return *this;
159 }
160 bool get() const {
161 CritScope scoped_lock(&cs_);
162 return flag_;
163 }
164
165 private:
pbos5ad935c2016-01-25 03:52:44 -0800166 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800167 bool flag_;
168};
169
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170// Function objects to test Thread::Invoke.
171struct FunctorA {
172 int operator()() { return 42; }
173};
174class FunctorB {
175 public:
nissed9b75be2015-11-16 00:54:07 -0800176 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200177 void operator()() {
178 if (flag_)
179 *flag_ = true;
180 }
181
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182 private:
nissed9b75be2015-11-16 00:54:07 -0800183 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184};
185struct FunctorC {
186 int operator()() {
187 Thread::Current()->ProcessMessages(50);
188 return 24;
189 }
190};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700191struct FunctorD {
192 public:
193 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
194 FunctorD(FunctorD&&) = default;
195 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200196 void operator()() {
197 if (flag_)
198 *flag_ = true;
199 }
200
Cameron Pickettd132ce12018-03-12 16:07:37 -0700201 private:
202 AtomicBool* flag_;
203 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
204};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205
206// See: https://code.google.com/p/webrtc/issues/detail?id=2409
207TEST(ThreadTest, DISABLED_Main) {
208 const SocketAddress addr("127.0.0.1", 0);
209
210 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700211 auto th1 = Thread::CreateWithSocketServer();
212 Socket* socket =
213 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
214 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215
216 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700217 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000218 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700219 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
220 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221
222 socket->Connect(sock_client.address());
223
tommie7251592017-07-14 14:44:46 -0700224 th1->Start();
225 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226
227 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700228 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 // Give the clients a little while to run.
231 // Messages will be processed at 100, 300, 500, 700, 900.
232 Thread* th_main = Thread::Current();
233 th_main->ProcessMessages(1000);
234
235 // Stop the sending client. Give the receiver a bit longer to run, in case
236 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700237 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700239 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
241 // Make sure the results were correct
242 EXPECT_EQ(5, msg_client.count);
243 EXPECT_EQ(34, msg_client.last);
244 EXPECT_EQ(5, sock_client.count);
245 EXPECT_EQ(55, sock_client.last);
246}
247
248// Test that setting thread names doesn't cause a malfunction.
249// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000250TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 // Default name
tommie7251592017-07-14 14:44:46 -0700252 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 EXPECT_TRUE(thread->Start());
254 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700256 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800257 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 EXPECT_TRUE(thread->Start());
259 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 // Really long name
tommie7251592017-07-14 14:44:46 -0700261 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
263 EXPECT_TRUE(thread->Start());
264 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265}
266
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000267TEST(ThreadTest, Wrap) {
268 Thread* current_thread = Thread::Current();
269 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 CustomThread* cthread = new CustomThread();
271 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000272 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 EXPECT_FALSE(cthread->IsOwned());
274 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000275 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000277 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278}
279
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000280TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700282 auto thread = Thread::CreateWithSocketServer();
283 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700285 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800286 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700288 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800289 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 // Try calling bare functions.
291 struct LocalFuncs {
292 static int Func1() { return 999; }
293 static void Func2() {}
294 };
tommie7251592017-07-14 14:44:46 -0700295 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
296 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297}
298
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000299// Verifies that two threads calling Invoke on each other at the same time does
300// not deadlock.
301TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
302 AutoThread thread;
303 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800304 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000305
tommie7251592017-07-14 14:44:46 -0700306 auto other_thread = Thread::CreateWithSocketServer();
307 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000308
309 struct LocalFuncs {
310 static void Set(bool* out) { *out = true; }
311 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700312 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000313 }
314 };
315
316 bool called = false;
tommie7251592017-07-14 14:44:46 -0700317 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700318 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000319
320 EXPECT_TRUE(called);
321}
322
323// Verifies that if thread A invokes a call on thread B and thread C is trying
324// to invoke A at the same time, thread A does not handle C's invoke while
325// invoking B.
326TEST(ThreadTest, ThreeThreadsInvoke) {
327 AutoThread thread;
328 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700329 auto thread_b = Thread::CreateWithSocketServer();
330 auto thread_c = Thread::CreateWithSocketServer();
331 thread_b->Start();
332 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000333
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000334 class LockedBool {
335 public:
336 explicit LockedBool(bool value) : value_(value) {}
337
338 void Set(bool value) {
339 CritScope lock(&crit_);
340 value_ = value;
341 }
342
343 bool Get() {
344 CritScope lock(&crit_);
345 return value_;
346 }
347
348 private:
349 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700350 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000351 };
352
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000353 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000354 static void Set(LockedBool* out) { out->Set(true); }
355 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700356 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000357 }
358
359 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000360 static void SetAndInvokeSet(LockedBool* out,
361 Thread* thread,
362 LockedBool* out_inner) {
363 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000364 InvokeSet(thread, out_inner);
365 }
366
367 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
368 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800369 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
370 Thread* thread1,
371 Thread* thread2,
372 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000373 CriticalSection crit;
374 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000375
deadbeef162cb532017-02-23 17:10:07 -0800376 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700377 RTC_FROM_HERE, thread1,
378 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000379
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000380 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000381 }
382 };
383
deadbeef162cb532017-02-23 17:10:07 -0800384 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000385 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000386
387 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
388 // Thread B returns when C receives the call and C should be blocked until A
389 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700390 thread_b->Invoke<void>(RTC_FROM_HERE,
391 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
392 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000393 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000394
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000395 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000396}
397
jbauch25d1f282016-02-05 00:25:02 -0800398// Set the name on a thread when the underlying QueueDestroyed signal is
399// triggered. This causes an error if the object is already partially
400// destroyed.
401class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
402 public:
403 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
404 thread->SignalQueueDestroyed.connect(
405 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
406 }
407
408 void OnQueueDestroyed() {
409 // Makes sure that if we access the Thread while it's being destroyed, that
410 // it doesn't cause a problem because the vtable has been modified.
411 thread_->SetName("foo", nullptr);
412 }
413
414 private:
415 Thread* thread_;
416};
417
418TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700419 auto thread1 = Thread::CreateWithSocketServer();
420 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
421 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800422
423 Thread* thread2 = new AutoThread();
424 SetNameOnSignalQueueDestroyedTester tester2(thread2);
425 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800426}
427
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428class AsyncInvokeTest : public testing::Test {
429 public:
430 void IntCallback(int value) {
431 EXPECT_EQ(expected_thread_, Thread::Current());
432 int_value_ = value;
433 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 void SetExpectedThreadForIntCallback(Thread* thread) {
435 expected_thread_ = thread;
436 }
437
438 protected:
439 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200440 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000441
442 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443 Thread* expected_thread_;
444};
445
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000446TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447 AsyncInvoker invoker;
448 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700449 auto thread = Thread::CreateWithSocketServer();
450 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800452 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700453 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800454 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700455 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000456}
457
Cameron Pickettd132ce12018-03-12 16:07:37 -0700458TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
459 AsyncInvoker invoker;
460 // Create and start the thread.
461 auto thread = Thread::CreateWithSocketServer();
462 thread->Start();
463 // Try calling functor.
464 AtomicBool called;
465 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
466 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
467 thread->Stop();
468}
469
deadbeef162cb532017-02-23 17:10:07 -0800470TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
471 // Use these events to get in a state where the functor is in the middle of
472 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
473 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100474 Event functor_started;
475 Event functor_continue;
476 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800477
tommie7251592017-07-14 14:44:46 -0700478 auto thread = Thread::CreateWithSocketServer();
479 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800480 volatile bool invoker_destroyed = false;
481 {
deadbeef3af63b02017-08-08 17:59:47 -0700482 auto functor = [&functor_started, &functor_continue, &functor_finished,
483 &invoker_destroyed] {
484 functor_started.Set();
485 functor_continue.Wait(Event::kForever);
486 rtc::Thread::Current()->SleepMs(kWaitTimeout);
487 EXPECT_FALSE(invoker_destroyed);
488 functor_finished.Set();
489 };
deadbeef162cb532017-02-23 17:10:07 -0800490 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700491 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800492 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700493
deadbeef3af63b02017-08-08 17:59:47 -0700494 // Destroy the invoker while the functor is still executing (doing
495 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700496 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800497 }
498
499 // If the destructor DIDN'T wait for the functor to finish executing, it will
500 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
501 // second.
502 invoker_destroyed = true;
503 functor_finished.Wait(Event::kForever);
504}
505
deadbeef3af63b02017-08-08 17:59:47 -0700506// Variant of the above test where the async-invoked task calls AsyncInvoke
507// *again*, for the thread on which the AsyncInvoker is currently being
508// destroyed. This shouldn't deadlock or crash; this second invocation should
509// just be ignored.
510TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100511 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700512 // Flag used to verify that the recursively invoked task never actually runs.
513 bool reentrant_functor_run = false;
514
515 Thread* main = Thread::Current();
516 Thread thread;
517 thread.Start();
518 {
519 AsyncInvoker invoker;
520 auto reentrant_functor = [&reentrant_functor_run] {
521 reentrant_functor_run = true;
522 };
523 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
524 functor_started.Set();
525 Thread::Current()->SleepMs(kWaitTimeout);
526 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
527 };
528 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
529 // task on |main|. But this second queued task should never run, since the
530 // destructor will be entered before it's even invoked.
531 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
532 functor_started.Wait(Event::kForever);
533 }
534 EXPECT_FALSE(reentrant_functor_run);
535}
536
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000537TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800539 AtomicBool flag1;
540 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700542 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
543 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800545 EXPECT_FALSE(flag1.get());
546 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547 // Force them to run now.
548 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800549 EXPECT_TRUE(flag1.get());
550 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551}
552
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000553TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800555 AtomicBool flag1;
556 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700558 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700560 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800562 EXPECT_FALSE(flag1.get());
563 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000564 // Execute pending calls with id == 5.
565 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800566 EXPECT_TRUE(flag1.get());
567 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000568 flag1 = false;
569 // Execute all pending calls. The id == 5 call should not execute again.
570 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800571 EXPECT_FALSE(flag1.get());
572 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000573}
574
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200575class GuardedAsyncInvokeTest : public testing::Test {
576 public:
577 void IntCallback(int value) {
578 EXPECT_EQ(expected_thread_, Thread::Current());
579 int_value_ = value;
580 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200581 void SetExpectedThreadForIntCallback(Thread* thread) {
582 expected_thread_ = thread;
583 }
584
585 protected:
586 const static int kWaitTimeout = 1000;
Yves Gerey665174f2018-06-19 15:03:05 +0200587 GuardedAsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200588
589 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200590 Thread* expected_thread_;
591};
592
593// Functor for creating an invoker.
594struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700595 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
596 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200597 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700598 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200599};
600
601// Test that we can call AsyncInvoke<void>() after the thread died.
602TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
603 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700604 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200605 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700606 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200607 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700608 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200609 // Kill |thread|.
610 thread = nullptr;
611 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800612 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700613 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200614 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800615 WAIT(called.get(), kWaitTimeout);
616 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200617}
618
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200619// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
620// when Thread is still alive.
621TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
622 GuardedAsyncInvoker invoker;
623 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800624 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700625 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800626 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200627}
628
Cameron Pickettd132ce12018-03-12 16:07:37 -0700629TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
630 GuardedAsyncInvoker invoker;
631 // Try calling functor.
632 AtomicBool called;
633 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
634 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
635}
636
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200637TEST_F(GuardedAsyncInvokeTest, Flush) {
638 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800639 AtomicBool flag1;
640 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200641 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700642 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
643 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200644 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800645 EXPECT_FALSE(flag1.get());
646 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200647 // Force them to run now.
648 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800649 EXPECT_TRUE(flag1.get());
650 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200651}
652
653TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
654 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800655 AtomicBool flag1;
656 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200657 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700658 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
659 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200660 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800661 EXPECT_FALSE(flag1.get());
662 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200663 // Execute pending calls with id == 5.
664 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800665 EXPECT_TRUE(flag1.get());
666 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200667 flag1 = false;
668 // Execute all pending calls. The id == 5 call should not execute again.
669 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800670 EXPECT_FALSE(flag1.get());
671 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200672}
Mirko Bonadeie10b1632018-12-11 18:43:40 +0100673
674} // namespace
675} // namespace rtc