• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
11 #include "rtc_base/thread.h"
12 
13 #include <memory>
14 
15 #include "api/task_queue/task_queue_factory.h"
16 #include "api/task_queue/task_queue_test.h"
17 #include "rtc_base/async_invoker.h"
18 #include "rtc_base/async_udp_socket.h"
19 #include "rtc_base/atomic_ops.h"
20 #include "rtc_base/event.h"
21 #include "rtc_base/gunit.h"
22 #include "rtc_base/null_socket_server.h"
23 #include "rtc_base/physical_socket_server.h"
24 #include "rtc_base/socket_address.h"
25 #include "rtc_base/synchronization/mutex.h"
26 #include "rtc_base/task_utils/to_queued_task.h"
27 #include "rtc_base/third_party/sigslot/sigslot.h"
28 #include "test/testsupport/rtc_expect_death.h"
29 
30 #if defined(WEBRTC_WIN)
31 #include <comdef.h>  // NOLINT
32 
33 #endif
34 
35 namespace rtc {
36 namespace {
37 
38 using ::webrtc::ToQueuedTask;
39 
40 // Generates a sequence of numbers (collaboratively).
41 class TestGenerator {
42  public:
TestGenerator()43   TestGenerator() : last(0), count(0) {}
44 
Next(int prev)45   int Next(int prev) {
46     int result = prev + last;
47     last = result;
48     count += 1;
49     return result;
50   }
51 
52   int last;
53   int count;
54 };
55 
56 struct TestMessage : public MessageData {
TestMessagertc::__anonec2f23eb0111::TestMessage57   explicit TestMessage(int v) : value(v) {}
58 
59   int value;
60 };
61 
62 // Receives on a socket and sends by posting messages.
63 class SocketClient : public TestGenerator, public sigslot::has_slots<> {
64  public:
SocketClient(AsyncSocket * socket,const SocketAddress & addr,Thread * post_thread,MessageHandler * phandler)65   SocketClient(AsyncSocket* socket,
66                const SocketAddress& addr,
67                Thread* post_thread,
68                MessageHandler* phandler)
69       : socket_(AsyncUDPSocket::Create(socket, addr)),
70         post_thread_(post_thread),
71         post_handler_(phandler) {
72     socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
73   }
74 
~SocketClient()75   ~SocketClient() override { delete socket_; }
76 
address() const77   SocketAddress address() const { return socket_->GetLocalAddress(); }
78 
OnPacket(AsyncPacketSocket * socket,const char * buf,size_t size,const SocketAddress & remote_addr,const int64_t & packet_time_us)79   void OnPacket(AsyncPacketSocket* socket,
80                 const char* buf,
81                 size_t size,
82                 const SocketAddress& remote_addr,
83                 const int64_t& packet_time_us) {
84     EXPECT_EQ(size, sizeof(uint32_t));
85     uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
86     uint32_t result = Next(prev);
87 
88     post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
89                               new TestMessage(result));
90   }
91 
92  private:
93   AsyncUDPSocket* socket_;
94   Thread* post_thread_;
95   MessageHandler* post_handler_;
96 };
97 
98 // Receives messages and sends on a socket.
99 class MessageClient : public MessageHandler, public TestGenerator {
100  public:
MessageClient(Thread * pth,Socket * socket)101   MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
102 
~MessageClient()103   ~MessageClient() override { delete socket_; }
104 
OnMessage(Message * pmsg)105   void OnMessage(Message* pmsg) override {
106     TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
107     int result = Next(msg->value);
108     EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
109     delete msg;
110   }
111 
112  private:
113   Socket* socket_;
114 };
115 
116 class CustomThread : public rtc::Thread {
117  public:
CustomThread()118   CustomThread()
119       : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
~CustomThread()120   ~CustomThread() override { Stop(); }
Start()121   bool Start() { return false; }
122 
WrapCurrent()123   bool WrapCurrent() { return Thread::WrapCurrent(); }
UnwrapCurrent()124   void UnwrapCurrent() { Thread::UnwrapCurrent(); }
125 };
126 
127 // A thread that does nothing when it runs and signals an event
128 // when it is destroyed.
129 class SignalWhenDestroyedThread : public Thread {
130  public:
SignalWhenDestroyedThread(Event * event)131   SignalWhenDestroyedThread(Event* event)
132       : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
133         event_(event) {}
134 
~SignalWhenDestroyedThread()135   ~SignalWhenDestroyedThread() override {
136     Stop();
137     event_->Set();
138   }
139 
Run()140   void Run() override {
141     // Do nothing.
142   }
143 
144  private:
145   Event* event_;
146 };
147 
148 // A bool wrapped in a mutex, to avoid data races. Using a volatile
149 // bool should be sufficient for correct code ("eventual consistency"
150 // between caches is sufficient), but we can't tell the compiler about
151 // that, and then tsan complains about a data race.
152 
153 // See also discussion at
154 // http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
155 
156 // Using std::atomic<bool> or std::atomic_flag in C++11 is probably
157 // the right thing to do, but those features are not yet allowed. Or
158 // rtc::AtomicInt, if/when that is added. Since the use isn't
159 // performance critical, use a plain critical section for the time
160 // being.
161 
162 class AtomicBool {
163  public:
AtomicBool(bool value=false)164   explicit AtomicBool(bool value = false) : flag_(value) {}
operator =(bool value)165   AtomicBool& operator=(bool value) {
166     webrtc::MutexLock scoped_lock(&mutex_);
167     flag_ = value;
168     return *this;
169   }
get() const170   bool get() const {
171     webrtc::MutexLock scoped_lock(&mutex_);
172     return flag_;
173   }
174 
175  private:
176   mutable webrtc::Mutex mutex_;
177   bool flag_;
178 };
179 
180 // Function objects to test Thread::Invoke.
181 struct FunctorA {
operator ()rtc::__anonec2f23eb0111::FunctorA182   int operator()() { return 42; }
183 };
184 class FunctorB {
185  public:
FunctorB(AtomicBool * flag)186   explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
operator ()()187   void operator()() {
188     if (flag_)
189       *flag_ = true;
190   }
191 
192  private:
193   AtomicBool* flag_;
194 };
195 struct FunctorC {
operator ()rtc::__anonec2f23eb0111::FunctorC196   int operator()() {
197     Thread::Current()->ProcessMessages(50);
198     return 24;
199   }
200 };
201 struct FunctorD {
202  public:
FunctorDrtc::__anonec2f23eb0111::FunctorD203   explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
204   FunctorD(FunctorD&&) = default;
205   FunctorD& operator=(FunctorD&&) = default;
operator ()rtc::__anonec2f23eb0111::FunctorD206   void operator()() {
207     if (flag_)
208       *flag_ = true;
209   }
210 
211  private:
212   AtomicBool* flag_;
213   RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
214 };
215 
216 // See: https://code.google.com/p/webrtc/issues/detail?id=2409
TEST(ThreadTest,DISABLED_Main)217 TEST(ThreadTest, DISABLED_Main) {
218   const SocketAddress addr("127.0.0.1", 0);
219 
220   // Create the messaging client on its own thread.
221   auto th1 = Thread::CreateWithSocketServer();
222   Socket* socket =
223       th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
224   MessageClient msg_client(th1.get(), socket);
225 
226   // Create the socket client on its own thread.
227   auto th2 = Thread::CreateWithSocketServer();
228   AsyncSocket* asocket =
229       th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
230   SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
231 
232   socket->Connect(sock_client.address());
233 
234   th1->Start();
235   th2->Start();
236 
237   // Get the messages started.
238   th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
239 
240   // Give the clients a little while to run.
241   // Messages will be processed at 100, 300, 500, 700, 900.
242   Thread* th_main = Thread::Current();
243   th_main->ProcessMessages(1000);
244 
245   // Stop the sending client. Give the receiver a bit longer to run, in case
246   // it is running on a machine that is under load (e.g. the build machine).
247   th1->Stop();
248   th_main->ProcessMessages(200);
249   th2->Stop();
250 
251   // Make sure the results were correct
252   EXPECT_EQ(5, msg_client.count);
253   EXPECT_EQ(34, msg_client.last);
254   EXPECT_EQ(5, sock_client.count);
255   EXPECT_EQ(55, sock_client.last);
256 }
257 
258 // Test that setting thread names doesn't cause a malfunction.
259 // There's no easy way to verify the name was set properly at this time.
TEST(ThreadTest,Names)260 TEST(ThreadTest, Names) {
261   // Default name
262   auto thread = Thread::CreateWithSocketServer();
263   EXPECT_TRUE(thread->Start());
264   thread->Stop();
265   // Name with no object parameter
266   thread = Thread::CreateWithSocketServer();
267   EXPECT_TRUE(thread->SetName("No object", nullptr));
268   EXPECT_TRUE(thread->Start());
269   thread->Stop();
270   // Really long name
271   thread = Thread::CreateWithSocketServer();
272   EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
273   EXPECT_TRUE(thread->Start());
274   thread->Stop();
275 }
276 
TEST(ThreadTest,Wrap)277 TEST(ThreadTest, Wrap) {
278   Thread* current_thread = Thread::Current();
279   ThreadManager::Instance()->SetCurrentThread(nullptr);
280 
281   {
282     CustomThread cthread;
283     EXPECT_TRUE(cthread.WrapCurrent());
284     EXPECT_EQ(&cthread, Thread::Current());
285     EXPECT_TRUE(cthread.RunningForTest());
286     EXPECT_FALSE(cthread.IsOwned());
287     cthread.UnwrapCurrent();
288     EXPECT_FALSE(cthread.RunningForTest());
289   }
290   ThreadManager::Instance()->SetCurrentThread(current_thread);
291 }
292 
293 #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
TEST(ThreadTest,InvokeToThreadAllowedReturnsTrueWithoutPolicies)294 TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
295   // Create and start the thread.
296   auto thread1 = Thread::CreateWithSocketServer();
297   auto thread2 = Thread::CreateWithSocketServer();
298 
299   thread1->PostTask(ToQueuedTask(
300       [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
301   Thread* th_main = Thread::Current();
302   th_main->ProcessMessages(100);
303 }
304 
TEST(ThreadTest,InvokeAllowedWhenThreadsAdded)305 TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
306   // Create and start the thread.
307   auto thread1 = Thread::CreateWithSocketServer();
308   auto thread2 = Thread::CreateWithSocketServer();
309   auto thread3 = Thread::CreateWithSocketServer();
310   auto thread4 = Thread::CreateWithSocketServer();
311 
312   thread1->AllowInvokesToThread(thread2.get());
313   thread1->AllowInvokesToThread(thread3.get());
314 
315   thread1->PostTask(ToQueuedTask([&]() {
316     EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
317     EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
318     EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
319   }));
320   Thread* th_main = Thread::Current();
321   th_main->ProcessMessages(100);
322 }
323 
TEST(ThreadTest,InvokesDisallowedWhenDisallowAllInvokes)324 TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
325   // Create and start the thread.
326   auto thread1 = Thread::CreateWithSocketServer();
327   auto thread2 = Thread::CreateWithSocketServer();
328 
329   thread1->DisallowAllInvokes();
330 
331   thread1->PostTask(ToQueuedTask([&]() {
332     EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
333   }));
334   Thread* th_main = Thread::Current();
335   th_main->ProcessMessages(100);
336 }
337 #endif  // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
338 
TEST(ThreadTest,InvokesAllowedByDefault)339 TEST(ThreadTest, InvokesAllowedByDefault) {
340   // Create and start the thread.
341   auto thread1 = Thread::CreateWithSocketServer();
342   auto thread2 = Thread::CreateWithSocketServer();
343 
344   thread1->PostTask(ToQueuedTask(
345       [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
346   Thread* th_main = Thread::Current();
347   th_main->ProcessMessages(100);
348 }
349 
TEST(ThreadTest,Invoke)350 TEST(ThreadTest, Invoke) {
351   // Create and start the thread.
352   auto thread = Thread::CreateWithSocketServer();
353   thread->Start();
354   // Try calling functors.
355   EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
356   AtomicBool called;
357   FunctorB f2(&called);
358   thread->Invoke<void>(RTC_FROM_HERE, f2);
359   EXPECT_TRUE(called.get());
360   // Try calling bare functions.
361   struct LocalFuncs {
362     static int Func1() { return 999; }
363     static void Func2() {}
364   };
365   EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
366   thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
367 }
368 
369 // Verifies that two threads calling Invoke on each other at the same time does
370 // not deadlock but crash.
371 #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
TEST(ThreadTest,TwoThreadsInvokeDeathTest)372 TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
373   ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
374   AutoThread thread;
375   Thread* main_thread = Thread::Current();
376   auto other_thread = Thread::CreateWithSocketServer();
377   other_thread->Start();
378   other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
379     RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
380   });
381 }
382 
TEST(ThreadTest,ThreeThreadsInvokeDeathTest)383 TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
384   ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
385   AutoThread thread;
386   Thread* first = Thread::Current();
387 
388   auto second = Thread::Create();
389   second->Start();
390   auto third = Thread::Create();
391   third->Start();
392 
393   second->Invoke<void>(RTC_FROM_HERE, [&] {
394     third->Invoke<void>(RTC_FROM_HERE, [&] {
395       RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
396     });
397   });
398 }
399 
400 #endif
401 
402 // Verifies that if thread A invokes a call on thread B and thread C is trying
403 // to invoke A at the same time, thread A does not handle C's invoke while
404 // invoking B.
TEST(ThreadTest,ThreeThreadsInvoke)405 TEST(ThreadTest, ThreeThreadsInvoke) {
406   AutoThread thread;
407   Thread* thread_a = Thread::Current();
408   auto thread_b = Thread::CreateWithSocketServer();
409   auto thread_c = Thread::CreateWithSocketServer();
410   thread_b->Start();
411   thread_c->Start();
412 
413   class LockedBool {
414    public:
415     explicit LockedBool(bool value) : value_(value) {}
416 
417     void Set(bool value) {
418       webrtc::MutexLock lock(&mutex_);
419       value_ = value;
420     }
421 
422     bool Get() {
423       webrtc::MutexLock lock(&mutex_);
424       return value_;
425     }
426 
427    private:
428     webrtc::Mutex mutex_;
429     bool value_ RTC_GUARDED_BY(mutex_);
430   };
431 
432   struct LocalFuncs {
433     static void Set(LockedBool* out) { out->Set(true); }
434     static void InvokeSet(Thread* thread, LockedBool* out) {
435       thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
436     }
437 
438     // Set |out| true and call InvokeSet on |thread|.
439     static void SetAndInvokeSet(LockedBool* out,
440                                 Thread* thread,
441                                 LockedBool* out_inner) {
442       out->Set(true);
443       InvokeSet(thread, out_inner);
444     }
445 
446     // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
447     // |thread1| starts the call.
448     static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
449                                       Thread* thread1,
450                                       Thread* thread2,
451                                       LockedBool* out) {
452       LockedBool async_invoked(false);
453 
454       invoker->AsyncInvoke<void>(
455           RTC_FROM_HERE, thread1,
456           Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
457 
458       EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
459     }
460   };
461 
462   AsyncInvoker invoker;
463   LockedBool thread_a_called(false);
464 
465   // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
466   // Thread B returns when C receives the call and C should be blocked until A
467   // starts to process messages.
468   thread_b->Invoke<void>(RTC_FROM_HERE,
469                          Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
470                               thread_c.get(), thread_a, &thread_a_called));
471   EXPECT_FALSE(thread_a_called.Get());
472 
473   EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
474 }
475 
476 // Set the name on a thread when the underlying QueueDestroyed signal is
477 // triggered. This causes an error if the object is already partially
478 // destroyed.
479 class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
480  public:
SetNameOnSignalQueueDestroyedTester(Thread * thread)481   SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
482     thread->SignalQueueDestroyed.connect(
483         this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
484   }
485 
OnQueueDestroyed()486   void OnQueueDestroyed() {
487     // Makes sure that if we access the Thread while it's being destroyed, that
488     // it doesn't cause a problem because the vtable has been modified.
489     thread_->SetName("foo", nullptr);
490   }
491 
492  private:
493   Thread* thread_;
494 };
495 
TEST(ThreadTest,SetNameOnSignalQueueDestroyed)496 TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
497   auto thread1 = Thread::CreateWithSocketServer();
498   SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
499   thread1.reset();
500 
501   Thread* thread2 = new AutoThread();
502   SetNameOnSignalQueueDestroyedTester tester2(thread2);
503   delete thread2;
504 }
505 
506 class ThreadQueueTest : public ::testing::Test, public Thread {
507  public:
ThreadQueueTest()508   ThreadQueueTest() : Thread(SocketServer::CreateDefault(), true) {}
IsLocked_Worker()509   bool IsLocked_Worker() {
510     if (!CritForTest()->TryEnter()) {
511       return true;
512     }
513     CritForTest()->Leave();
514     return false;
515   }
IsLocked()516   bool IsLocked() {
517     // We have to do this on a worker thread, or else the TryEnter will
518     // succeed, since our critical sections are reentrant.
519     std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
520     worker->Start();
521     return worker->Invoke<bool>(
522         RTC_FROM_HERE, rtc::Bind(&ThreadQueueTest::IsLocked_Worker, this));
523   }
524 };
525 
526 struct DeletedLockChecker {
DeletedLockCheckerrtc::__anonec2f23eb0111::DeletedLockChecker527   DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
528       : test(test), was_locked(was_locked), deleted(deleted) {}
~DeletedLockCheckerrtc::__anonec2f23eb0111::DeletedLockChecker529   ~DeletedLockChecker() {
530     *deleted = true;
531     *was_locked = test->IsLocked();
532   }
533   ThreadQueueTest* test;
534   bool* was_locked;
535   bool* deleted;
536 };
537 
DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread * q)538 static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
539   EXPECT_TRUE(q != nullptr);
540   int64_t now = TimeMillis();
541   q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
542   q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
543   q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
544   q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
545   q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
546 
547   Message msg;
548   for (size_t i = 0; i < 5; ++i) {
549     memset(&msg, 0, sizeof(msg));
550     EXPECT_TRUE(q->Get(&msg, 0));
551     EXPECT_EQ(i, msg.message_id);
552   }
553 
554   EXPECT_FALSE(q->Get(&msg, 0));  // No more messages
555 }
556 
TEST_F(ThreadQueueTest,DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder)557 TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
558   Thread q(SocketServer::CreateDefault(), true);
559   DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
560 
561   NullSocketServer nullss;
562   Thread q_nullss(&nullss, true);
563   DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
564 }
565 
TEST_F(ThreadQueueTest,DisposeNotLocked)566 TEST_F(ThreadQueueTest, DisposeNotLocked) {
567   bool was_locked = true;
568   bool deleted = false;
569   DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
570   Dispose(d);
571   Message msg;
572   EXPECT_FALSE(Get(&msg, 0));
573   EXPECT_TRUE(deleted);
574   EXPECT_FALSE(was_locked);
575 }
576 
577 class DeletedMessageHandler : public MessageHandler {
578  public:
DeletedMessageHandler(bool * deleted)579   explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
~DeletedMessageHandler()580   ~DeletedMessageHandler() override { *deleted_ = true; }
OnMessage(Message * msg)581   void OnMessage(Message* msg) override {}
582 
583  private:
584   bool* deleted_;
585 };
586 
TEST_F(ThreadQueueTest,DiposeHandlerWithPostedMessagePending)587 TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
588   bool deleted = false;
589   DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
590   // First, post a dispose.
591   Dispose(handler);
592   // Now, post a message, which should *not* be returned by Get().
593   Post(RTC_FROM_HERE, handler, 1);
594   Message msg;
595   EXPECT_FALSE(Get(&msg, 0));
596   EXPECT_TRUE(deleted);
597 }
598 
599 // Ensure that ProcessAllMessageQueues does its essential function; process
600 // all messages (both delayed and non delayed) up until the current time, on
601 // all registered message queues.
TEST(ThreadManager,ProcessAllMessageQueues)602 TEST(ThreadManager, ProcessAllMessageQueues) {
603   Event entered_process_all_message_queues(true, false);
604   auto a = Thread::CreateWithSocketServer();
605   auto b = Thread::CreateWithSocketServer();
606   a->Start();
607   b->Start();
608 
609   volatile int messages_processed = 0;
610   auto incrementer = [&messages_processed,
611                       &entered_process_all_message_queues] {
612     // Wait for event as a means to ensure Increment doesn't occur outside
613     // of ProcessAllMessageQueues. The event is set by a message posted to
614     // the main thread, which is guaranteed to be handled inside
615     // ProcessAllMessageQueues.
616     entered_process_all_message_queues.Wait(Event::kForever);
617     AtomicOps::Increment(&messages_processed);
618   };
619   auto event_signaler = [&entered_process_all_message_queues] {
620     entered_process_all_message_queues.Set();
621   };
622 
623   // Post messages (both delayed and non delayed) to both threads.
624   a->PostTask(ToQueuedTask(incrementer));
625   b->PostTask(ToQueuedTask(incrementer));
626   a->PostDelayedTask(ToQueuedTask(incrementer), 0);
627   b->PostDelayedTask(ToQueuedTask(incrementer), 0);
628   rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
629 
630   ThreadManager::ProcessAllMessageQueuesForTesting();
631   EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
632 }
633 
634 // Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
TEST(ThreadManager,ProcessAllMessageQueuesWithQuittingThread)635 TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
636   auto t = Thread::CreateWithSocketServer();
637   t->Start();
638   t->Quit();
639   ThreadManager::ProcessAllMessageQueuesForTesting();
640 }
641 
642 // Test that ProcessAllMessageQueues doesn't hang if a queue clears its
643 // messages.
TEST(ThreadManager,ProcessAllMessageQueuesWithClearedQueue)644 TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
645   Event entered_process_all_message_queues(true, false);
646   auto t = Thread::CreateWithSocketServer();
647   t->Start();
648 
649   auto clearer = [&entered_process_all_message_queues] {
650     // Wait for event as a means to ensure Clear doesn't occur outside of
651     // ProcessAllMessageQueues. The event is set by a message posted to the
652     // main thread, which is guaranteed to be handled inside
653     // ProcessAllMessageQueues.
654     entered_process_all_message_queues.Wait(Event::kForever);
655     rtc::Thread::Current()->Clear(nullptr);
656   };
657   auto event_signaler = [&entered_process_all_message_queues] {
658     entered_process_all_message_queues.Set();
659   };
660 
661   // Post messages (both delayed and non delayed) to both threads.
662   t->PostTask(RTC_FROM_HERE, clearer);
663   rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
664   ThreadManager::ProcessAllMessageQueuesForTesting();
665 }
666 
667 class RefCountedHandler : public MessageHandler, public rtc::RefCountInterface {
668  public:
OnMessage(Message * msg)669   void OnMessage(Message* msg) override {}
670 };
671 
672 class EmptyHandler : public MessageHandler {
673  public:
OnMessage(Message * msg)674   void OnMessage(Message* msg) override {}
675 };
676 
TEST(ThreadManager,ClearReentrant)677 TEST(ThreadManager, ClearReentrant) {
678   std::unique_ptr<Thread> t(Thread::Create());
679   EmptyHandler handler;
680   RefCountedHandler* inner_handler(
681       new rtc::RefCountedObject<RefCountedHandler>());
682   // When the empty handler is destroyed, it will clear messages queued for
683   // itself. The message to be cleared itself wraps a MessageHandler object
684   // (RefCountedHandler) so this will cause the message queue to be cleared
685   // again in a re-entrant fashion, which previously triggered a DCHECK.
686   // The inner handler will be removed in a re-entrant fashion from the
687   // message queue of the thread while the outer handler is removed, verifying
688   // that the iterator is not invalidated in "MessageQueue::Clear".
689   t->Post(RTC_FROM_HERE, inner_handler, 0);
690   t->Post(RTC_FROM_HERE, &handler, 0,
691           new ScopedRefMessageData<RefCountedHandler>(inner_handler));
692 }
693 
694 class AsyncInvokeTest : public ::testing::Test {
695  public:
IntCallback(int value)696   void IntCallback(int value) {
697     EXPECT_EQ(expected_thread_, Thread::Current());
698     int_value_ = value;
699   }
SetExpectedThreadForIntCallback(Thread * thread)700   void SetExpectedThreadForIntCallback(Thread* thread) {
701     expected_thread_ = thread;
702   }
703 
704  protected:
705   enum { kWaitTimeout = 1000 };
AsyncInvokeTest()706   AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
707 
708   int int_value_;
709   Thread* expected_thread_;
710 };
711 
TEST_F(AsyncInvokeTest,FireAndForget)712 TEST_F(AsyncInvokeTest, FireAndForget) {
713   AsyncInvoker invoker;
714   // Create and start the thread.
715   auto thread = Thread::CreateWithSocketServer();
716   thread->Start();
717   // Try calling functor.
718   AtomicBool called;
719   invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
720   EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
721   thread->Stop();
722 }
723 
TEST_F(AsyncInvokeTest,NonCopyableFunctor)724 TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
725   AsyncInvoker invoker;
726   // Create and start the thread.
727   auto thread = Thread::CreateWithSocketServer();
728   thread->Start();
729   // Try calling functor.
730   AtomicBool called;
731   invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
732   EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
733   thread->Stop();
734 }
735 
TEST_F(AsyncInvokeTest,KillInvokerDuringExecute)736 TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
737   // Use these events to get in a state where the functor is in the middle of
738   // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
739   // is run.
740   Event functor_started;
741   Event functor_continue;
742   Event functor_finished;
743 
744   auto thread = Thread::CreateWithSocketServer();
745   thread->Start();
746   volatile bool invoker_destroyed = false;
747   {
748     auto functor = [&functor_started, &functor_continue, &functor_finished,
749                     &invoker_destroyed] {
750       functor_started.Set();
751       functor_continue.Wait(Event::kForever);
752       rtc::Thread::Current()->SleepMs(kWaitTimeout);
753       EXPECT_FALSE(invoker_destroyed);
754       functor_finished.Set();
755     };
756     AsyncInvoker invoker;
757     invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
758     functor_started.Wait(Event::kForever);
759 
760     // Destroy the invoker while the functor is still executing (doing
761     // SleepMs).
762     functor_continue.Set();
763   }
764 
765   // If the destructor DIDN'T wait for the functor to finish executing, it will
766   // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
767   // second.
768   invoker_destroyed = true;
769   functor_finished.Wait(Event::kForever);
770 }
771 
772 // Variant of the above test where the async-invoked task calls AsyncInvoke
773 // *again*, for the thread on which the AsyncInvoker is currently being
774 // destroyed. This shouldn't deadlock or crash; this second invocation should
775 // just be ignored.
TEST_F(AsyncInvokeTest,KillInvokerDuringExecuteWithReentrantInvoke)776 TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
777   Event functor_started;
778   // Flag used to verify that the recursively invoked task never actually runs.
779   bool reentrant_functor_run = false;
780 
781   Thread* main = Thread::Current();
782   Thread thread(std::make_unique<NullSocketServer>());
783   thread.Start();
784   {
785     AsyncInvoker invoker;
786     auto reentrant_functor = [&reentrant_functor_run] {
787       reentrant_functor_run = true;
788     };
789     auto functor = [&functor_started, &invoker, main, reentrant_functor] {
790       functor_started.Set();
791       Thread::Current()->SleepMs(kWaitTimeout);
792       invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
793     };
794     // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
795     // task on |main|. But this second queued task should never run, since the
796     // destructor will be entered before it's even invoked.
797     invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
798     functor_started.Wait(Event::kForever);
799   }
800   EXPECT_FALSE(reentrant_functor_run);
801 }
802 
TEST_F(AsyncInvokeTest,Flush)803 TEST_F(AsyncInvokeTest, Flush) {
804   AsyncInvoker invoker;
805   AtomicBool flag1;
806   AtomicBool flag2;
807   // Queue two async calls to the current thread.
808   invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
809   invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
810   // Because we haven't pumped messages, these should not have run yet.
811   EXPECT_FALSE(flag1.get());
812   EXPECT_FALSE(flag2.get());
813   // Force them to run now.
814   invoker.Flush(Thread::Current());
815   EXPECT_TRUE(flag1.get());
816   EXPECT_TRUE(flag2.get());
817 }
818 
TEST_F(AsyncInvokeTest,FlushWithIds)819 TEST_F(AsyncInvokeTest, FlushWithIds) {
820   AsyncInvoker invoker;
821   AtomicBool flag1;
822   AtomicBool flag2;
823   // Queue two async calls to the current thread, one with a message id.
824   invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
825                             5);
826   invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
827   // Because we haven't pumped messages, these should not have run yet.
828   EXPECT_FALSE(flag1.get());
829   EXPECT_FALSE(flag2.get());
830   // Execute pending calls with id == 5.
831   invoker.Flush(Thread::Current(), 5);
832   EXPECT_TRUE(flag1.get());
833   EXPECT_FALSE(flag2.get());
834   flag1 = false;
835   // Execute all pending calls. The id == 5 call should not execute again.
836   invoker.Flush(Thread::Current());
837   EXPECT_FALSE(flag1.get());
838   EXPECT_TRUE(flag2.get());
839 }
840 
ThreadIsCurrent(Thread * thread,bool * result,Event * event)841 void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
842   *result = thread->IsCurrent();
843   event->Set();
844 }
845 
WaitAndSetEvent(Event * wait_event,Event * set_event)846 void WaitAndSetEvent(Event* wait_event, Event* set_event) {
847   wait_event->Wait(Event::kForever);
848   set_event->Set();
849 }
850 
851 // A functor that keeps track of the number of copies and moves.
852 class LifeCycleFunctor {
853  public:
854   struct Stats {
855     size_t copy_count = 0;
856     size_t move_count = 0;
857   };
858 
LifeCycleFunctor(Stats * stats,Event * event)859   LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
LifeCycleFunctor(const LifeCycleFunctor & other)860   LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
LifeCycleFunctor(LifeCycleFunctor && other)861   LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
862 
operator =(const LifeCycleFunctor & other)863   LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
864     stats_ = other.stats_;
865     event_ = other.event_;
866     ++stats_->copy_count;
867     return *this;
868   }
869 
operator =(LifeCycleFunctor && other)870   LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
871     stats_ = other.stats_;
872     event_ = other.event_;
873     ++stats_->move_count;
874     return *this;
875   }
876 
operator ()()877   void operator()() { event_->Set(); }
878 
879  private:
880   Stats* stats_;
881   Event* event_;
882 };
883 
884 // A functor that verifies the thread it was destroyed on.
885 class DestructionFunctor {
886  public:
DestructionFunctor(Thread * thread,bool * thread_was_current,Event * event)887   DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
888       : thread_(thread),
889         thread_was_current_(thread_was_current),
890         event_(event) {}
~DestructionFunctor()891   ~DestructionFunctor() {
892     // Only signal the event if this was the functor that was invoked to avoid
893     // the event being signaled due to the destruction of temporary/moved
894     // versions of this object.
895     if (was_invoked_) {
896       *thread_was_current_ = thread_->IsCurrent();
897       event_->Set();
898     }
899   }
900 
operator ()()901   void operator()() { was_invoked_ = true; }
902 
903  private:
904   Thread* thread_;
905   bool* thread_was_current_;
906   Event* event_;
907   bool was_invoked_ = false;
908 };
909 
TEST(ThreadPostTaskTest,InvokesWithBind)910 TEST(ThreadPostTaskTest, InvokesWithBind) {
911   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
912   background_thread->Start();
913 
914   Event event;
915   background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
916   event.Wait(Event::kForever);
917 }
918 
TEST(ThreadPostTaskTest,InvokesWithLambda)919 TEST(ThreadPostTaskTest, InvokesWithLambda) {
920   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
921   background_thread->Start();
922 
923   Event event;
924   background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
925   event.Wait(Event::kForever);
926 }
927 
TEST(ThreadPostTaskTest,InvokesWithCopiedFunctor)928 TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
929   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
930   background_thread->Start();
931 
932   LifeCycleFunctor::Stats stats;
933   Event event;
934   LifeCycleFunctor functor(&stats, &event);
935   background_thread->PostTask(RTC_FROM_HERE, functor);
936   event.Wait(Event::kForever);
937 
938   EXPECT_EQ(1u, stats.copy_count);
939   EXPECT_EQ(0u, stats.move_count);
940 }
941 
TEST(ThreadPostTaskTest,InvokesWithMovedFunctor)942 TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
943   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
944   background_thread->Start();
945 
946   LifeCycleFunctor::Stats stats;
947   Event event;
948   LifeCycleFunctor functor(&stats, &event);
949   background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
950   event.Wait(Event::kForever);
951 
952   EXPECT_EQ(0u, stats.copy_count);
953   EXPECT_EQ(1u, stats.move_count);
954 }
955 
TEST(ThreadPostTaskTest,InvokesWithReferencedFunctorShouldCopy)956 TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
957   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
958   background_thread->Start();
959 
960   LifeCycleFunctor::Stats stats;
961   Event event;
962   LifeCycleFunctor functor(&stats, &event);
963   LifeCycleFunctor& functor_ref = functor;
964   background_thread->PostTask(RTC_FROM_HERE, functor_ref);
965   event.Wait(Event::kForever);
966 
967   EXPECT_EQ(1u, stats.copy_count);
968   EXPECT_EQ(0u, stats.move_count);
969 }
970 
TEST(ThreadPostTaskTest,InvokesWithCopiedFunctorDestroyedOnTargetThread)971 TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
972   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
973   background_thread->Start();
974 
975   Event event;
976   bool was_invoked_on_background_thread = false;
977   DestructionFunctor functor(background_thread.get(),
978                              &was_invoked_on_background_thread, &event);
979   background_thread->PostTask(RTC_FROM_HERE, functor);
980   event.Wait(Event::kForever);
981 
982   EXPECT_TRUE(was_invoked_on_background_thread);
983 }
984 
TEST(ThreadPostTaskTest,InvokesWithMovedFunctorDestroyedOnTargetThread)985 TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
986   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
987   background_thread->Start();
988 
989   Event event;
990   bool was_invoked_on_background_thread = false;
991   DestructionFunctor functor(background_thread.get(),
992                              &was_invoked_on_background_thread, &event);
993   background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
994   event.Wait(Event::kForever);
995 
996   EXPECT_TRUE(was_invoked_on_background_thread);
997 }
998 
TEST(ThreadPostTaskTest,InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread)999 TEST(ThreadPostTaskTest,
1000      InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1001   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1002   background_thread->Start();
1003 
1004   Event event;
1005   bool was_invoked_on_background_thread = false;
1006   DestructionFunctor functor(background_thread.get(),
1007                              &was_invoked_on_background_thread, &event);
1008   DestructionFunctor& functor_ref = functor;
1009   background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1010   event.Wait(Event::kForever);
1011 
1012   EXPECT_TRUE(was_invoked_on_background_thread);
1013 }
1014 
TEST(ThreadPostTaskTest,InvokesOnBackgroundThread)1015 TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1016   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1017   background_thread->Start();
1018 
1019   Event event;
1020   bool was_invoked_on_background_thread = false;
1021   background_thread->PostTask(RTC_FROM_HERE,
1022                               Bind(&ThreadIsCurrent, background_thread.get(),
1023                                    &was_invoked_on_background_thread, &event));
1024   event.Wait(Event::kForever);
1025 
1026   EXPECT_TRUE(was_invoked_on_background_thread);
1027 }
1028 
TEST(ThreadPostTaskTest,InvokesAsynchronously)1029 TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1030   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1031   background_thread->Start();
1032 
1033   // The first event ensures that SendSingleMessage() is not blocking this
1034   // thread. The second event ensures that the message is processed.
1035   Event event_set_by_test_thread;
1036   Event event_set_by_background_thread;
1037   background_thread->PostTask(RTC_FROM_HERE,
1038                               Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1039                                    &event_set_by_background_thread));
1040   event_set_by_test_thread.Set();
1041   event_set_by_background_thread.Wait(Event::kForever);
1042 }
1043 
TEST(ThreadPostTaskTest,InvokesInPostedOrder)1044 TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1045   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1046   background_thread->Start();
1047 
1048   Event first;
1049   Event second;
1050   Event third;
1051   Event fourth;
1052 
1053   background_thread->PostTask(RTC_FROM_HERE,
1054                               Bind(&WaitAndSetEvent, &first, &second));
1055   background_thread->PostTask(RTC_FROM_HERE,
1056                               Bind(&WaitAndSetEvent, &second, &third));
1057   background_thread->PostTask(RTC_FROM_HERE,
1058                               Bind(&WaitAndSetEvent, &third, &fourth));
1059 
1060   // All tasks have been posted before the first one is unblocked.
1061   first.Set();
1062   // Only if the chain is invoked in posted order will the last event be set.
1063   fourth.Wait(Event::kForever);
1064 }
1065 
TEST(ThreadPostDelayedTaskTest,InvokesAsynchronously)1066 TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1067   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1068   background_thread->Start();
1069 
1070   // The first event ensures that SendSingleMessage() is not blocking this
1071   // thread. The second event ensures that the message is processed.
1072   Event event_set_by_test_thread;
1073   Event event_set_by_background_thread;
1074   background_thread->PostDelayedTask(
1075       RTC_FROM_HERE,
1076       Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1077            &event_set_by_background_thread),
1078       /*milliseconds=*/10);
1079   event_set_by_test_thread.Set();
1080   event_set_by_background_thread.Wait(Event::kForever);
1081 }
1082 
TEST(ThreadPostDelayedTaskTest,InvokesInDelayOrder)1083 TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
1084   ScopedFakeClock clock;
1085   std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1086   background_thread->Start();
1087 
1088   Event first;
1089   Event second;
1090   Event third;
1091   Event fourth;
1092 
1093   background_thread->PostDelayedTask(RTC_FROM_HERE,
1094                                      Bind(&WaitAndSetEvent, &third, &fourth),
1095                                      /*milliseconds=*/11);
1096   background_thread->PostDelayedTask(RTC_FROM_HERE,
1097                                      Bind(&WaitAndSetEvent, &first, &second),
1098                                      /*milliseconds=*/9);
1099   background_thread->PostDelayedTask(RTC_FROM_HERE,
1100                                      Bind(&WaitAndSetEvent, &second, &third),
1101                                      /*milliseconds=*/10);
1102 
1103   // All tasks have been posted before the first one is unblocked.
1104   first.Set();
1105   // Only if the chain is invoked in delay order will the last event be set.
1106   clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
1107   EXPECT_TRUE(fourth.Wait(0));
1108 }
1109 
TEST(ThreadPostDelayedTaskTest,IsCurrentTaskQueue)1110 TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1111   auto current_tq = webrtc::TaskQueueBase::Current();
1112   {
1113     std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1114     thread->WrapCurrent();
1115     EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1116               static_cast<webrtc::TaskQueueBase*>(thread.get()));
1117     thread->UnwrapCurrent();
1118   }
1119   EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1120 }
1121 
1122 class ThreadFactory : public webrtc::TaskQueueFactory {
1123  public:
1124   std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
CreateTaskQueue(absl::string_view,Priority) const1125   CreateTaskQueue(absl::string_view /* name */,
1126                   Priority /*priority*/) const override {
1127     std::unique_ptr<Thread> thread = Thread::Create();
1128     thread->Start();
1129     return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1130         thread.release());
1131   }
1132 };
1133 
1134 using ::webrtc::TaskQueueTest;
1135 
1136 INSTANTIATE_TEST_SUITE_P(RtcThread,
1137                          TaskQueueTest,
1138                          ::testing::Values(std::make_unique<ThreadFactory>));
1139 
1140 }  // namespace
1141 }  // namespace rtc
1142