blob: d5c53f8a7cc0a27fc4fa647bf97d1cf6f29cc2ec [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
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 21:53:4611#include <memory>
12
Mirko Bonadei92ea95e2017-09-15 04:47:3113#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"
Mirko Bonadei92ea95e2017-09-15 04:47:3119#include "rtc_base/socketaddress.h"
Artem Titove41c4332018-07-25 13:04:2820#include "rtc_base/third_party/sigslot/sigslot.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3121#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:2622
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:2647
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:
Yves Gerey665174f2018-06-19 13:03:0554 SocketClient(AsyncSocket* socket,
55 const SocketAddress& addr,
56 Thread* post_thread,
57 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:2658 : socket_(AsyncUDPSocket::Create(socket, addr)),
59 post_thread_(post_thread),
60 post_handler_(phandler) {
61 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
62 }
63
Steve Anton9de3aac2017-10-24 17:08:2664 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:2665
66 SocketAddress address() const { return socket_->GetLocalAddress(); }
67
Yves Gerey665174f2018-06-19 13:03:0568 void OnPacket(AsyncPacketSocket* socket,
69 const char* buf,
70 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:2671 const SocketAddress& remote_addr,
72 const PacketTime& packet_time) {
Peter Boström0c4e06b2015-10-07 10:23:2173 EXPECT_EQ(size, sizeof(uint32_t));
74 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
75 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:2676
Taylor Brandstetter5d97a9a2016-06-10 21:17:2777 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
78 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:2679 }
80
81 private:
82 AsyncUDPSocket* socket_;
83 Thread* post_thread_;
84 MessageHandler* post_handler_;
85};
86
87// Receives messages and sends on a socket.
88class MessageClient : public MessageHandler, public TestGenerator {
89 public:
Yves Gerey665174f2018-06-19 13:03:0590 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:2691
Steve Anton9de3aac2017-10-24 17:08:2692 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:2693
Steve Anton9de3aac2017-10-24 17:08:2694 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:2695 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
96 int result = Next(msg->value);
97 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
98 delete msg;
99 }
100
101 private:
102 Socket* socket_;
103};
104
deadbeefaea92932017-05-23 19:55:03105class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26106 public:
tommie7251592017-07-14 21:44:46107 CustomThread()
108 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 17:08:26109 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26110 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21111
Yves Gerey665174f2018-06-19 13:03:05112 bool WrapCurrent() { return Thread::WrapCurrent(); }
113 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26114};
115
henrike@webrtc.orgf0488722014-05-13 18:00:26116// A thread that does nothing when it runs and signals an event
117// when it is destroyed.
118class SignalWhenDestroyedThread : public Thread {
119 public:
120 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 21:44:46121 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
122 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26123
Steve Anton9de3aac2017-10-24 17:08:26124 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26125 Stop();
126 event_->Set();
127 }
128
Steve Anton9de3aac2017-10-24 17:08:26129 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26130 // Do nothing.
131 }
132
133 private:
134 Event* event_;
135};
136
nissed9b75be2015-11-16 08:54:07137// A bool wrapped in a mutex, to avoid data races. Using a volatile
138// bool should be sufficient for correct code ("eventual consistency"
139// between caches is sufficient), but we can't tell the compiler about
140// that, and then tsan complains about a data race.
141
142// See also discussion at
143// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
144
145// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
146// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 19:55:03147// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 08:54:07148// performance critical, use a plain critical section for the time
149// being.
150
151class AtomicBool {
152 public:
153 explicit AtomicBool(bool value = false) : flag_(value) {}
154 AtomicBool& operator=(bool value) {
155 CritScope scoped_lock(&cs_);
156 flag_ = value;
157 return *this;
158 }
159 bool get() const {
160 CritScope scoped_lock(&cs_);
161 return flag_;
162 }
163
164 private:
pbos5ad935c2016-01-25 11:52:44165 CriticalSection cs_;
nissed9b75be2015-11-16 08:54:07166 bool flag_;
167};
168
henrike@webrtc.orgf0488722014-05-13 18:00:26169// Function objects to test Thread::Invoke.
170struct FunctorA {
171 int operator()() { return 42; }
172};
173class FunctorB {
174 public:
nissed9b75be2015-11-16 08:54:07175 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 13:03:05176 void operator()() {
177 if (flag_)
178 *flag_ = true;
179 }
180
henrike@webrtc.orgf0488722014-05-13 18:00:26181 private:
nissed9b75be2015-11-16 08:54:07182 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26183};
184struct FunctorC {
185 int operator()() {
186 Thread::Current()->ProcessMessages(50);
187 return 24;
188 }
189};
Cameron Pickettd132ce12018-03-12 23:07:37190struct FunctorD {
191 public:
192 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
193 FunctorD(FunctorD&&) = default;
194 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 13:03:05195 void operator()() {
196 if (flag_)
197 *flag_ = true;
198 }
199
Cameron Pickettd132ce12018-03-12 23:07:37200 private:
201 AtomicBool* flag_;
202 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
203};
henrike@webrtc.orgf0488722014-05-13 18:00:26204
205// See: https://code.google.com/p/webrtc/issues/detail?id=2409
206TEST(ThreadTest, DISABLED_Main) {
207 const SocketAddress addr("127.0.0.1", 0);
208
209 // Create the messaging client on its own thread.
tommie7251592017-07-14 21:44:46210 auto th1 = Thread::CreateWithSocketServer();
211 Socket* socket =
212 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
213 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26214
215 // Create the socket client on its own thread.
tommie7251592017-07-14 21:44:46216 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26217 AsyncSocket* asocket =
tommie7251592017-07-14 21:44:46218 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
219 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26220
221 socket->Connect(sock_client.address());
222
tommie7251592017-07-14 21:44:46223 th1->Start();
224 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26225
226 // Get the messages started.
tommie7251592017-07-14 21:44:46227 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26228
229 // Give the clients a little while to run.
230 // Messages will be processed at 100, 300, 500, 700, 900.
231 Thread* th_main = Thread::Current();
232 th_main->ProcessMessages(1000);
233
234 // Stop the sending client. Give the receiver a bit longer to run, in case
235 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 21:44:46236 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26237 th_main->ProcessMessages(200);
tommie7251592017-07-14 21:44:46238 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26239
240 // Make sure the results were correct
241 EXPECT_EQ(5, msg_client.count);
242 EXPECT_EQ(34, msg_client.last);
243 EXPECT_EQ(5, sock_client.count);
244 EXPECT_EQ(55, sock_client.last);
245}
246
247// Test that setting thread names doesn't cause a malfunction.
248// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15249TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26250 // Default name
tommie7251592017-07-14 21:44:46251 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26252 EXPECT_TRUE(thread->Start());
253 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26254 // Name with no object parameter
tommie7251592017-07-14 21:44:46255 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 22:06:41256 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26257 EXPECT_TRUE(thread->Start());
258 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26259 // Really long name
tommie7251592017-07-14 21:44:46260 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26261 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
262 EXPECT_TRUE(thread->Start());
263 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26264}
265
henrike@webrtc.orge30dab72014-10-09 15:41:40266TEST(ThreadTest, Wrap) {
267 Thread* current_thread = Thread::Current();
268 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26269 CustomThread* cthread = new CustomThread();
270 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50271 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26272 EXPECT_FALSE(cthread->IsOwned());
273 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50274 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26275 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40276 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26277}
278
henrike@webrtc.orgc732a3e2014-10-09 22:08:15279TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26280 // Create and start the thread.
tommie7251592017-07-14 21:44:46281 auto thread = Thread::CreateWithSocketServer();
282 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26283 // Try calling functors.
tommie7251592017-07-14 21:44:46284 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 08:54:07285 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26286 FunctorB f2(&called);
tommie7251592017-07-14 21:44:46287 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 08:54:07288 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26289 // Try calling bare functions.
290 struct LocalFuncs {
291 static int Func1() { return 999; }
292 static void Func2() {}
293 };
tommie7251592017-07-14 21:44:46294 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
295 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26296}
297
jiayl@webrtc.org3987b6d2014-09-24 17:14:05298// Verifies that two threads calling Invoke on each other at the same time does
299// not deadlock.
300TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
301 AutoThread thread;
302 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 22:06:41303 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05304
tommie7251592017-07-14 21:44:46305 auto other_thread = Thread::CreateWithSocketServer();
306 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05307
308 struct LocalFuncs {
309 static void Set(bool* out) { *out = true; }
310 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 21:17:27311 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05312 }
313 };
314
315 bool called = false;
tommie7251592017-07-14 21:44:46316 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27317 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05318
319 EXPECT_TRUE(called);
320}
321
322// Verifies that if thread A invokes a call on thread B and thread C is trying
323// to invoke A at the same time, thread A does not handle C's invoke while
324// invoking B.
325TEST(ThreadTest, ThreeThreadsInvoke) {
326 AutoThread thread;
327 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 21:44:46328 auto thread_b = Thread::CreateWithSocketServer();
329 auto thread_c = Thread::CreateWithSocketServer();
330 thread_b->Start();
331 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05332
pbos@webrtc.orge93cbd12014-10-15 14:54:56333 class LockedBool {
334 public:
335 explicit LockedBool(bool value) : value_(value) {}
336
337 void Set(bool value) {
338 CritScope lock(&crit_);
339 value_ = value;
340 }
341
342 bool Get() {
343 CritScope lock(&crit_);
344 return value_;
345 }
346
347 private:
348 CriticalSection crit_;
danilchap3c6abd22017-09-06 12:46:29349 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56350 };
351
jiayl@webrtc.org3987b6d2014-09-24 17:14:05352 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56353 static void Set(LockedBool* out) { out->Set(true); }
354 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 21:17:27355 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05356 }
357
358 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56359 static void SetAndInvokeSet(LockedBool* out,
360 Thread* thread,
361 LockedBool* out_inner) {
362 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05363 InvokeSet(thread, out_inner);
364 }
365
366 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
367 // |thread1| starts the call.
deadbeef162cb532017-02-24 01:10:07368 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
369 Thread* thread1,
370 Thread* thread2,
371 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56372 CriticalSection crit;
373 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05374
deadbeef162cb532017-02-24 01:10:07375 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27376 RTC_FROM_HERE, thread1,
377 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05378
pbos@webrtc.orge93cbd12014-10-15 14:54:56379 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05380 }
381 };
382
deadbeef162cb532017-02-24 01:10:07383 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56384 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05385
386 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
387 // Thread B returns when C receives the call and C should be blocked until A
388 // starts to process messages.
tommie7251592017-07-14 21:44:46389 thread_b->Invoke<void>(RTC_FROM_HERE,
390 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
391 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56392 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05393
pbos@webrtc.orge93cbd12014-10-15 14:54:56394 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05395}
396
jbauch25d1f282016-02-05 08:25:02397// Set the name on a thread when the underlying QueueDestroyed signal is
398// triggered. This causes an error if the object is already partially
399// destroyed.
400class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
401 public:
402 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
403 thread->SignalQueueDestroyed.connect(
404 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
405 }
406
407 void OnQueueDestroyed() {
408 // Makes sure that if we access the Thread while it's being destroyed, that
409 // it doesn't cause a problem because the vtable has been modified.
410 thread_->SetName("foo", nullptr);
411 }
412
413 private:
414 Thread* thread_;
415};
416
417TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 21:44:46418 auto thread1 = Thread::CreateWithSocketServer();
419 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
420 thread1.reset();
jbauch25d1f282016-02-05 08:25:02421
422 Thread* thread2 = new AutoThread();
423 SetNameOnSignalQueueDestroyedTester tester2(thread2);
424 delete thread2;
jbauch25d1f282016-02-05 08:25:02425}
426
henrike@webrtc.orgf0488722014-05-13 18:00:26427class AsyncInvokeTest : public testing::Test {
428 public:
429 void IntCallback(int value) {
430 EXPECT_EQ(expected_thread_, Thread::Current());
431 int_value_ = value;
432 }
henrike@webrtc.orgf0488722014-05-13 18:00:26433 void SetExpectedThreadForIntCallback(Thread* thread) {
434 expected_thread_ = thread;
435 }
436
437 protected:
438 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 13:03:05439 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26440
441 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26442 Thread* expected_thread_;
443};
444
henrike@webrtc.orge30dab72014-10-09 15:41:40445TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26446 AsyncInvoker invoker;
447 // Create and start the thread.
tommie7251592017-07-14 21:44:46448 auto thread = Thread::CreateWithSocketServer();
449 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26450 // Try calling functor.
nissed9b75be2015-11-16 08:54:07451 AtomicBool called;
tommie7251592017-07-14 21:44:46452 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 08:54:07453 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 21:44:46454 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26455}
456
Cameron Pickettd132ce12018-03-12 23:07:37457TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
458 AsyncInvoker invoker;
459 // Create and start the thread.
460 auto thread = Thread::CreateWithSocketServer();
461 thread->Start();
462 // Try calling functor.
463 AtomicBool called;
464 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
465 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
466 thread->Stop();
467}
468
deadbeef162cb532017-02-24 01:10:07469TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
470 // Use these events to get in a state where the functor is in the middle of
471 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
472 // is run.
473 Event functor_started(false, false);
deadbeefaea92932017-05-23 19:55:03474 Event functor_continue(false, false);
deadbeef162cb532017-02-24 01:10:07475 Event functor_finished(false, false);
476
tommie7251592017-07-14 21:44:46477 auto thread = Thread::CreateWithSocketServer();
478 thread->Start();
deadbeef162cb532017-02-24 01:10:07479 volatile bool invoker_destroyed = false;
480 {
deadbeef3af63b02017-08-09 00:59:47481 auto functor = [&functor_started, &functor_continue, &functor_finished,
482 &invoker_destroyed] {
483 functor_started.Set();
484 functor_continue.Wait(Event::kForever);
485 rtc::Thread::Current()->SleepMs(kWaitTimeout);
486 EXPECT_FALSE(invoker_destroyed);
487 functor_finished.Set();
488 };
deadbeef162cb532017-02-24 01:10:07489 AsyncInvoker invoker;
deadbeef3af63b02017-08-09 00:59:47490 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-24 01:10:07491 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 19:55:03492
deadbeef3af63b02017-08-09 00:59:47493 // Destroy the invoker while the functor is still executing (doing
494 // SleepMs).
deadbeefaea92932017-05-23 19:55:03495 functor_continue.Set();
deadbeef162cb532017-02-24 01:10:07496 }
497
498 // If the destructor DIDN'T wait for the functor to finish executing, it will
499 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
500 // second.
501 invoker_destroyed = true;
502 functor_finished.Wait(Event::kForever);
503}
504
deadbeef3af63b02017-08-09 00:59:47505// Variant of the above test where the async-invoked task calls AsyncInvoke
506// *again*, for the thread on which the AsyncInvoker is currently being
507// destroyed. This shouldn't deadlock or crash; this second invocation should
508// just be ignored.
509TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
510 Event functor_started(false, false);
511 // Flag used to verify that the recursively invoked task never actually runs.
512 bool reentrant_functor_run = false;
513
514 Thread* main = Thread::Current();
515 Thread thread;
516 thread.Start();
517 {
518 AsyncInvoker invoker;
519 auto reentrant_functor = [&reentrant_functor_run] {
520 reentrant_functor_run = true;
521 };
522 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
523 functor_started.Set();
524 Thread::Current()->SleepMs(kWaitTimeout);
525 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
526 };
527 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
528 // task on |main|. But this second queued task should never run, since the
529 // destructor will be entered before it's even invoked.
530 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
531 functor_started.Wait(Event::kForever);
532 }
533 EXPECT_FALSE(reentrant_functor_run);
534}
535
henrike@webrtc.orgc732a3e2014-10-09 22:08:15536TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26537 AsyncInvoker invoker;
nissed9b75be2015-11-16 08:54:07538 AtomicBool flag1;
539 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26540 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27541 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
542 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26543 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 08:54:07544 EXPECT_FALSE(flag1.get());
545 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26546 // Force them to run now.
547 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 08:54:07548 EXPECT_TRUE(flag1.get());
549 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26550}
551
henrike@webrtc.orgc732a3e2014-10-09 22:08:15552TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26553 AsyncInvoker invoker;
nissed9b75be2015-11-16 08:54:07554 AtomicBool flag1;
555 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26556 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27557 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26558 5);
Taylor Brandstetter5d97a9a2016-06-10 21:17:27559 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26560 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 08:54:07561 EXPECT_FALSE(flag1.get());
562 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26563 // Execute pending calls with id == 5.
564 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 08:54:07565 EXPECT_TRUE(flag1.get());
566 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26567 flag1 = false;
568 // Execute all pending calls. The id == 5 call should not execute again.
569 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 08:54:07570 EXPECT_FALSE(flag1.get());
571 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26572}
573
Magnus Jedverta1f590f2015-08-20 14:42:42574class GuardedAsyncInvokeTest : public testing::Test {
575 public:
576 void IntCallback(int value) {
577 EXPECT_EQ(expected_thread_, Thread::Current());
578 int_value_ = value;
579 }
Magnus Jedverta1f590f2015-08-20 14:42:42580 void SetExpectedThreadForIntCallback(Thread* thread) {
581 expected_thread_ = thread;
582 }
583
584 protected:
585 const static int kWaitTimeout = 1000;
Yves Gerey665174f2018-06-19 13:03:05586 GuardedAsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
Magnus Jedverta1f590f2015-08-20 14:42:42587
588 int int_value_;
Magnus Jedverta1f590f2015-08-20 14:42:42589 Thread* expected_thread_;
590};
591
592// Functor for creating an invoker.
593struct CreateInvoker {
jbauch555604a2016-04-26 10:13:22594 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
595 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 14:42:42596 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 10:13:22597 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 14:42:42598};
599
600// Test that we can call AsyncInvoke<void>() after the thread died.
601TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
602 // Create and start the thread.
tommie7251592017-07-14 21:44:46603 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 14:42:42604 thread->Start();
jbauch555604a2016-04-26 10:13:22605 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 14:42:42606 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27607 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 14:42:42608 // Kill |thread|.
609 thread = nullptr;
610 // Try calling functor.
nissed9b75be2015-11-16 08:54:07611 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 21:17:27612 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 14:42:42613 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 08:54:07614 WAIT(called.get(), kWaitTimeout);
615 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 14:42:42616}
617
Magnus Jedverta1f590f2015-08-20 14:42:42618// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
619// when Thread is still alive.
620TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
621 GuardedAsyncInvoker invoker;
622 // Try calling functor.
nissed9b75be2015-11-16 08:54:07623 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 21:17:27624 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 08:54:07625 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 14:42:42626}
627
Cameron Pickettd132ce12018-03-12 23:07:37628TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
629 GuardedAsyncInvoker invoker;
630 // Try calling functor.
631 AtomicBool called;
632 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
633 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
634}
635
Magnus Jedverta1f590f2015-08-20 14:42:42636TEST_F(GuardedAsyncInvokeTest, Flush) {
637 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 08:54:07638 AtomicBool flag1;
639 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 14:42:42640 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27641 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
642 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 14:42:42643 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 08:54:07644 EXPECT_FALSE(flag1.get());
645 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 14:42:42646 // Force them to run now.
647 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 08:54:07648 EXPECT_TRUE(flag1.get());
649 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 14:42:42650}
651
652TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
653 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 08:54:07654 AtomicBool flag1;
655 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 14:42:42656 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27657 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
658 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 14:42:42659 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 08:54:07660 EXPECT_FALSE(flag1.get());
661 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 14:42:42662 // Execute pending calls with id == 5.
663 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 08:54:07664 EXPECT_TRUE(flag1.get());
665 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 14:42:42666 flag1 = false;
667 // Execute all pending calls. The id == 5 call should not execute again.
668 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 08:54:07669 EXPECT_FALSE(flag1.get());
670 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 14:42:42671}