You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

904 lines
28 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "rtc_base/thread.h"
  11. #include <memory>
  12. #include "rtc_base/async_invoker.h"
  13. #include "rtc_base/async_udp_socket.h"
  14. #include "rtc_base/event.h"
  15. #include "rtc_base/gunit.h"
  16. #include "rtc_base/null_socket_server.h"
  17. #include "rtc_base/physical_socket_server.h"
  18. #include "rtc_base/socket_address.h"
  19. #include "rtc_base/third_party/sigslot/sigslot.h"
  20. #if defined(WEBRTC_WIN)
  21. #include <comdef.h> // NOLINT
  22. #endif
  23. namespace rtc {
  24. namespace {
  25. // Generates a sequence of numbers (collaboratively).
  26. class TestGenerator {
  27. public:
  28. TestGenerator() : last(0), count(0) {}
  29. int Next(int prev) {
  30. int result = prev + last;
  31. last = result;
  32. count += 1;
  33. return result;
  34. }
  35. int last;
  36. int count;
  37. };
  38. struct TestMessage : public MessageData {
  39. explicit TestMessage(int v) : value(v) {}
  40. int value;
  41. };
  42. // Receives on a socket and sends by posting messages.
  43. class SocketClient : public TestGenerator, public sigslot::has_slots<> {
  44. public:
  45. SocketClient(AsyncSocket* socket,
  46. const SocketAddress& addr,
  47. Thread* post_thread,
  48. MessageHandler* phandler)
  49. : socket_(AsyncUDPSocket::Create(socket, addr)),
  50. post_thread_(post_thread),
  51. post_handler_(phandler) {
  52. socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
  53. }
  54. ~SocketClient() override { delete socket_; }
  55. SocketAddress address() const { return socket_->GetLocalAddress(); }
  56. void OnPacket(AsyncPacketSocket* socket,
  57. const char* buf,
  58. size_t size,
  59. const SocketAddress& remote_addr,
  60. const int64_t& packet_time_us) {
  61. EXPECT_EQ(size, sizeof(uint32_t));
  62. uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
  63. uint32_t result = Next(prev);
  64. post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
  65. new TestMessage(result));
  66. }
  67. private:
  68. AsyncUDPSocket* socket_;
  69. Thread* post_thread_;
  70. MessageHandler* post_handler_;
  71. };
  72. // Receives messages and sends on a socket.
  73. class MessageClient : public MessageHandler, public TestGenerator {
  74. public:
  75. MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
  76. ~MessageClient() override { delete socket_; }
  77. void OnMessage(Message* pmsg) override {
  78. TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
  79. int result = Next(msg->value);
  80. EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
  81. delete msg;
  82. }
  83. private:
  84. Socket* socket_;
  85. };
  86. class CustomThread : public rtc::Thread {
  87. public:
  88. CustomThread()
  89. : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
  90. ~CustomThread() override { Stop(); }
  91. bool Start() { return false; }
  92. bool WrapCurrent() { return Thread::WrapCurrent(); }
  93. void UnwrapCurrent() { Thread::UnwrapCurrent(); }
  94. };
  95. // A thread that does nothing when it runs and signals an event
  96. // when it is destroyed.
  97. class SignalWhenDestroyedThread : public Thread {
  98. public:
  99. SignalWhenDestroyedThread(Event* event)
  100. : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
  101. event_(event) {}
  102. ~SignalWhenDestroyedThread() override {
  103. Stop();
  104. event_->Set();
  105. }
  106. void Run() override {
  107. // Do nothing.
  108. }
  109. private:
  110. Event* event_;
  111. };
  112. // A bool wrapped in a mutex, to avoid data races. Using a volatile
  113. // bool should be sufficient for correct code ("eventual consistency"
  114. // between caches is sufficient), but we can't tell the compiler about
  115. // that, and then tsan complains about a data race.
  116. // See also discussion at
  117. // http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
  118. // Using std::atomic<bool> or std::atomic_flag in C++11 is probably
  119. // the right thing to do, but those features are not yet allowed. Or
  120. // rtc::AtomicInt, if/when that is added. Since the use isn't
  121. // performance critical, use a plain critical section for the time
  122. // being.
  123. class AtomicBool {
  124. public:
  125. explicit AtomicBool(bool value = false) : flag_(value) {}
  126. AtomicBool& operator=(bool value) {
  127. CritScope scoped_lock(&cs_);
  128. flag_ = value;
  129. return *this;
  130. }
  131. bool get() const {
  132. CritScope scoped_lock(&cs_);
  133. return flag_;
  134. }
  135. private:
  136. CriticalSection cs_;
  137. bool flag_;
  138. };
  139. // Function objects to test Thread::Invoke.
  140. struct FunctorA {
  141. int operator()() { return 42; }
  142. };
  143. class FunctorB {
  144. public:
  145. explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
  146. void operator()() {
  147. if (flag_)
  148. *flag_ = true;
  149. }
  150. private:
  151. AtomicBool* flag_;
  152. };
  153. struct FunctorC {
  154. int operator()() {
  155. Thread::Current()->ProcessMessages(50);
  156. return 24;
  157. }
  158. };
  159. struct FunctorD {
  160. public:
  161. explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
  162. FunctorD(FunctorD&&) = default;
  163. FunctorD& operator=(FunctorD&&) = default;
  164. void operator()() {
  165. if (flag_)
  166. *flag_ = true;
  167. }
  168. private:
  169. AtomicBool* flag_;
  170. RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
  171. };
  172. // See: https://code.google.com/p/webrtc/issues/detail?id=2409
  173. TEST(ThreadTest, DISABLED_Main) {
  174. const SocketAddress addr("127.0.0.1", 0);
  175. // Create the messaging client on its own thread.
  176. auto th1 = Thread::CreateWithSocketServer();
  177. Socket* socket =
  178. th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
  179. MessageClient msg_client(th1.get(), socket);
  180. // Create the socket client on its own thread.
  181. auto th2 = Thread::CreateWithSocketServer();
  182. AsyncSocket* asocket =
  183. th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
  184. SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
  185. socket->Connect(sock_client.address());
  186. th1->Start();
  187. th2->Start();
  188. // Get the messages started.
  189. th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
  190. // Give the clients a little while to run.
  191. // Messages will be processed at 100, 300, 500, 700, 900.
  192. Thread* th_main = Thread::Current();
  193. th_main->ProcessMessages(1000);
  194. // Stop the sending client. Give the receiver a bit longer to run, in case
  195. // it is running on a machine that is under load (e.g. the build machine).
  196. th1->Stop();
  197. th_main->ProcessMessages(200);
  198. th2->Stop();
  199. // Make sure the results were correct
  200. EXPECT_EQ(5, msg_client.count);
  201. EXPECT_EQ(34, msg_client.last);
  202. EXPECT_EQ(5, sock_client.count);
  203. EXPECT_EQ(55, sock_client.last);
  204. }
  205. // Test that setting thread names doesn't cause a malfunction.
  206. // There's no easy way to verify the name was set properly at this time.
  207. TEST(ThreadTest, Names) {
  208. // Default name
  209. auto thread = Thread::CreateWithSocketServer();
  210. EXPECT_TRUE(thread->Start());
  211. thread->Stop();
  212. // Name with no object parameter
  213. thread = Thread::CreateWithSocketServer();
  214. EXPECT_TRUE(thread->SetName("No object", nullptr));
  215. EXPECT_TRUE(thread->Start());
  216. thread->Stop();
  217. // Really long name
  218. thread = Thread::CreateWithSocketServer();
  219. EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
  220. EXPECT_TRUE(thread->Start());
  221. thread->Stop();
  222. }
  223. TEST(ThreadTest, Wrap) {
  224. Thread* current_thread = Thread::Current();
  225. ThreadManager::Instance()->SetCurrentThread(nullptr);
  226. {
  227. CustomThread cthread;
  228. EXPECT_TRUE(cthread.WrapCurrent());
  229. EXPECT_EQ(&cthread, Thread::Current());
  230. EXPECT_TRUE(cthread.RunningForTest());
  231. EXPECT_FALSE(cthread.IsOwned());
  232. cthread.UnwrapCurrent();
  233. EXPECT_FALSE(cthread.RunningForTest());
  234. }
  235. ThreadManager::Instance()->SetCurrentThread(current_thread);
  236. }
  237. TEST(ThreadTest, Invoke) {
  238. // Create and start the thread.
  239. auto thread = Thread::CreateWithSocketServer();
  240. thread->Start();
  241. // Try calling functors.
  242. EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
  243. AtomicBool called;
  244. FunctorB f2(&called);
  245. thread->Invoke<void>(RTC_FROM_HERE, f2);
  246. EXPECT_TRUE(called.get());
  247. // Try calling bare functions.
  248. struct LocalFuncs {
  249. static int Func1() { return 999; }
  250. static void Func2() {}
  251. };
  252. EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
  253. thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
  254. }
  255. // Verifies that two threads calling Invoke on each other at the same time does
  256. // not deadlock.
  257. TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
  258. AutoThread thread;
  259. Thread* current_thread = Thread::Current();
  260. ASSERT_TRUE(current_thread != nullptr);
  261. auto other_thread = Thread::CreateWithSocketServer();
  262. other_thread->Start();
  263. struct LocalFuncs {
  264. static void Set(bool* out) { *out = true; }
  265. static void InvokeSet(Thread* thread, bool* out) {
  266. thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
  267. }
  268. };
  269. bool called = false;
  270. other_thread->Invoke<void>(
  271. RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
  272. EXPECT_TRUE(called);
  273. }
  274. // Verifies that if thread A invokes a call on thread B and thread C is trying
  275. // to invoke A at the same time, thread A does not handle C's invoke while
  276. // invoking B.
  277. TEST(ThreadTest, ThreeThreadsInvoke) {
  278. AutoThread thread;
  279. Thread* thread_a = Thread::Current();
  280. auto thread_b = Thread::CreateWithSocketServer();
  281. auto thread_c = Thread::CreateWithSocketServer();
  282. thread_b->Start();
  283. thread_c->Start();
  284. class LockedBool {
  285. public:
  286. explicit LockedBool(bool value) : value_(value) {}
  287. void Set(bool value) {
  288. CritScope lock(&crit_);
  289. value_ = value;
  290. }
  291. bool Get() {
  292. CritScope lock(&crit_);
  293. return value_;
  294. }
  295. private:
  296. CriticalSection crit_;
  297. bool value_ RTC_GUARDED_BY(crit_);
  298. };
  299. struct LocalFuncs {
  300. static void Set(LockedBool* out) { out->Set(true); }
  301. static void InvokeSet(Thread* thread, LockedBool* out) {
  302. thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
  303. }
  304. // Set |out| true and call InvokeSet on |thread|.
  305. static void SetAndInvokeSet(LockedBool* out,
  306. Thread* thread,
  307. LockedBool* out_inner) {
  308. out->Set(true);
  309. InvokeSet(thread, out_inner);
  310. }
  311. // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
  312. // |thread1| starts the call.
  313. static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
  314. Thread* thread1,
  315. Thread* thread2,
  316. LockedBool* out) {
  317. CriticalSection crit;
  318. LockedBool async_invoked(false);
  319. invoker->AsyncInvoke<void>(
  320. RTC_FROM_HERE, thread1,
  321. Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
  322. EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
  323. }
  324. };
  325. AsyncInvoker invoker;
  326. LockedBool thread_a_called(false);
  327. // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
  328. // Thread B returns when C receives the call and C should be blocked until A
  329. // starts to process messages.
  330. thread_b->Invoke<void>(RTC_FROM_HERE,
  331. Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
  332. thread_c.get(), thread_a, &thread_a_called));
  333. EXPECT_FALSE(thread_a_called.Get());
  334. EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
  335. }
  336. // Set the name on a thread when the underlying QueueDestroyed signal is
  337. // triggered. This causes an error if the object is already partially
  338. // destroyed.
  339. class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
  340. public:
  341. SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
  342. thread->SignalQueueDestroyed.connect(
  343. this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
  344. }
  345. void OnQueueDestroyed() {
  346. // Makes sure that if we access the Thread while it's being destroyed, that
  347. // it doesn't cause a problem because the vtable has been modified.
  348. thread_->SetName("foo", nullptr);
  349. }
  350. private:
  351. Thread* thread_;
  352. };
  353. TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
  354. auto thread1 = Thread::CreateWithSocketServer();
  355. SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
  356. thread1.reset();
  357. Thread* thread2 = new AutoThread();
  358. SetNameOnSignalQueueDestroyedTester tester2(thread2);
  359. delete thread2;
  360. }
  361. class AsyncInvokeTest : public ::testing::Test {
  362. public:
  363. void IntCallback(int value) {
  364. EXPECT_EQ(expected_thread_, Thread::Current());
  365. int_value_ = value;
  366. }
  367. void SetExpectedThreadForIntCallback(Thread* thread) {
  368. expected_thread_ = thread;
  369. }
  370. protected:
  371. enum { kWaitTimeout = 1000 };
  372. AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
  373. int int_value_;
  374. Thread* expected_thread_;
  375. };
  376. TEST_F(AsyncInvokeTest, FireAndForget) {
  377. AsyncInvoker invoker;
  378. // Create and start the thread.
  379. auto thread = Thread::CreateWithSocketServer();
  380. thread->Start();
  381. // Try calling functor.
  382. AtomicBool called;
  383. invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
  384. EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
  385. thread->Stop();
  386. }
  387. TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
  388. AsyncInvoker invoker;
  389. // Create and start the thread.
  390. auto thread = Thread::CreateWithSocketServer();
  391. thread->Start();
  392. // Try calling functor.
  393. AtomicBool called;
  394. invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
  395. EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
  396. thread->Stop();
  397. }
  398. TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
  399. // Use these events to get in a state where the functor is in the middle of
  400. // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
  401. // is run.
  402. Event functor_started;
  403. Event functor_continue;
  404. Event functor_finished;
  405. auto thread = Thread::CreateWithSocketServer();
  406. thread->Start();
  407. volatile bool invoker_destroyed = false;
  408. {
  409. auto functor = [&functor_started, &functor_continue, &functor_finished,
  410. &invoker_destroyed] {
  411. functor_started.Set();
  412. functor_continue.Wait(Event::kForever);
  413. rtc::Thread::Current()->SleepMs(kWaitTimeout);
  414. EXPECT_FALSE(invoker_destroyed);
  415. functor_finished.Set();
  416. };
  417. AsyncInvoker invoker;
  418. invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
  419. functor_started.Wait(Event::kForever);
  420. // Destroy the invoker while the functor is still executing (doing
  421. // SleepMs).
  422. functor_continue.Set();
  423. }
  424. // If the destructor DIDN'T wait for the functor to finish executing, it will
  425. // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
  426. // second.
  427. invoker_destroyed = true;
  428. functor_finished.Wait(Event::kForever);
  429. }
  430. // Variant of the above test where the async-invoked task calls AsyncInvoke
  431. // *again*, for the thread on which the AsyncInvoker is currently being
  432. // destroyed. This shouldn't deadlock or crash; this second invocation should
  433. // just be ignored.
  434. TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
  435. Event functor_started;
  436. // Flag used to verify that the recursively invoked task never actually runs.
  437. bool reentrant_functor_run = false;
  438. Thread* main = Thread::Current();
  439. Thread thread(std::make_unique<NullSocketServer>());
  440. thread.Start();
  441. {
  442. AsyncInvoker invoker;
  443. auto reentrant_functor = [&reentrant_functor_run] {
  444. reentrant_functor_run = true;
  445. };
  446. auto functor = [&functor_started, &invoker, main, reentrant_functor] {
  447. functor_started.Set();
  448. Thread::Current()->SleepMs(kWaitTimeout);
  449. invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
  450. };
  451. // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
  452. // task on |main|. But this second queued task should never run, since the
  453. // destructor will be entered before it's even invoked.
  454. invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
  455. functor_started.Wait(Event::kForever);
  456. }
  457. EXPECT_FALSE(reentrant_functor_run);
  458. }
  459. TEST_F(AsyncInvokeTest, Flush) {
  460. AsyncInvoker invoker;
  461. AtomicBool flag1;
  462. AtomicBool flag2;
  463. // Queue two async calls to the current thread.
  464. invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
  465. invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
  466. // Because we haven't pumped messages, these should not have run yet.
  467. EXPECT_FALSE(flag1.get());
  468. EXPECT_FALSE(flag2.get());
  469. // Force them to run now.
  470. invoker.Flush(Thread::Current());
  471. EXPECT_TRUE(flag1.get());
  472. EXPECT_TRUE(flag2.get());
  473. }
  474. TEST_F(AsyncInvokeTest, FlushWithIds) {
  475. AsyncInvoker invoker;
  476. AtomicBool flag1;
  477. AtomicBool flag2;
  478. // Queue two async calls to the current thread, one with a message id.
  479. invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
  480. 5);
  481. invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
  482. // Because we haven't pumped messages, these should not have run yet.
  483. EXPECT_FALSE(flag1.get());
  484. EXPECT_FALSE(flag2.get());
  485. // Execute pending calls with id == 5.
  486. invoker.Flush(Thread::Current(), 5);
  487. EXPECT_TRUE(flag1.get());
  488. EXPECT_FALSE(flag2.get());
  489. flag1 = false;
  490. // Execute all pending calls. The id == 5 call should not execute again.
  491. invoker.Flush(Thread::Current());
  492. EXPECT_FALSE(flag1.get());
  493. EXPECT_TRUE(flag2.get());
  494. }
  495. class GuardedAsyncInvokeTest : public ::testing::Test {
  496. public:
  497. void IntCallback(int value) {
  498. EXPECT_EQ(expected_thread_, Thread::Current());
  499. int_value_ = value;
  500. }
  501. void SetExpectedThreadForIntCallback(Thread* thread) {
  502. expected_thread_ = thread;
  503. }
  504. protected:
  505. const static int kWaitTimeout = 1000;
  506. GuardedAsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
  507. int int_value_;
  508. Thread* expected_thread_;
  509. };
  510. // Functor for creating an invoker.
  511. struct CreateInvoker {
  512. CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
  513. : invoker_(invoker) {}
  514. void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
  515. std::unique_ptr<GuardedAsyncInvoker>* invoker_;
  516. };
  517. // Test that we can call AsyncInvoke<void>() after the thread died.
  518. TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
  519. // Create and start the thread.
  520. std::unique_ptr<Thread> thread(Thread::Create());
  521. thread->Start();
  522. std::unique_ptr<GuardedAsyncInvoker> invoker;
  523. // Create the invoker on |thread|.
  524. thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
  525. // Kill |thread|.
  526. thread = nullptr;
  527. // Try calling functor.
  528. AtomicBool called;
  529. EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
  530. // With thread gone, nothing should happen.
  531. WAIT(called.get(), kWaitTimeout);
  532. EXPECT_FALSE(called.get());
  533. }
  534. // The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
  535. // when Thread is still alive.
  536. TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
  537. GuardedAsyncInvoker invoker;
  538. // Try calling functor.
  539. AtomicBool called;
  540. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
  541. EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
  542. }
  543. TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
  544. GuardedAsyncInvoker invoker;
  545. // Try calling functor.
  546. AtomicBool called;
  547. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
  548. EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
  549. }
  550. TEST_F(GuardedAsyncInvokeTest, Flush) {
  551. GuardedAsyncInvoker invoker;
  552. AtomicBool flag1;
  553. AtomicBool flag2;
  554. // Queue two async calls to the current thread.
  555. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
  556. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
  557. // Because we haven't pumped messages, these should not have run yet.
  558. EXPECT_FALSE(flag1.get());
  559. EXPECT_FALSE(flag2.get());
  560. // Force them to run now.
  561. EXPECT_TRUE(invoker.Flush());
  562. EXPECT_TRUE(flag1.get());
  563. EXPECT_TRUE(flag2.get());
  564. }
  565. TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
  566. GuardedAsyncInvoker invoker;
  567. AtomicBool flag1;
  568. AtomicBool flag2;
  569. // Queue two async calls to the current thread, one with a message id.
  570. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
  571. EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
  572. // Because we haven't pumped messages, these should not have run yet.
  573. EXPECT_FALSE(flag1.get());
  574. EXPECT_FALSE(flag2.get());
  575. // Execute pending calls with id == 5.
  576. EXPECT_TRUE(invoker.Flush(5));
  577. EXPECT_TRUE(flag1.get());
  578. EXPECT_FALSE(flag2.get());
  579. flag1 = false;
  580. // Execute all pending calls. The id == 5 call should not execute again.
  581. EXPECT_TRUE(invoker.Flush());
  582. EXPECT_FALSE(flag1.get());
  583. EXPECT_TRUE(flag2.get());
  584. }
  585. void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
  586. *result = thread->IsCurrent();
  587. event->Set();
  588. }
  589. void WaitAndSetEvent(Event* wait_event, Event* set_event) {
  590. wait_event->Wait(Event::kForever);
  591. set_event->Set();
  592. }
  593. // A functor that keeps track of the number of copies and moves.
  594. class LifeCycleFunctor {
  595. public:
  596. struct Stats {
  597. size_t copy_count = 0;
  598. size_t move_count = 0;
  599. };
  600. LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
  601. LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
  602. LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
  603. LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
  604. stats_ = other.stats_;
  605. event_ = other.event_;
  606. ++stats_->copy_count;
  607. return *this;
  608. }
  609. LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
  610. stats_ = other.stats_;
  611. event_ = other.event_;
  612. ++stats_->move_count;
  613. return *this;
  614. }
  615. void operator()() { event_->Set(); }
  616. private:
  617. Stats* stats_;
  618. Event* event_;
  619. };
  620. // A functor that verifies the thread it was destroyed on.
  621. class DestructionFunctor {
  622. public:
  623. DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
  624. : thread_(thread),
  625. thread_was_current_(thread_was_current),
  626. event_(event) {}
  627. ~DestructionFunctor() {
  628. // Only signal the event if this was the functor that was invoked to avoid
  629. // the event being signaled due to the destruction of temporary/moved
  630. // versions of this object.
  631. if (was_invoked_) {
  632. *thread_was_current_ = thread_->IsCurrent();
  633. event_->Set();
  634. }
  635. }
  636. void operator()() { was_invoked_ = true; }
  637. private:
  638. Thread* thread_;
  639. bool* thread_was_current_;
  640. Event* event_;
  641. bool was_invoked_ = false;
  642. };
  643. TEST(ThreadPostTaskTest, InvokesWithBind) {
  644. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  645. background_thread->Start();
  646. Event event;
  647. background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
  648. event.Wait(Event::kForever);
  649. }
  650. TEST(ThreadPostTaskTest, InvokesWithLambda) {
  651. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  652. background_thread->Start();
  653. Event event;
  654. background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
  655. event.Wait(Event::kForever);
  656. }
  657. TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
  658. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  659. background_thread->Start();
  660. LifeCycleFunctor::Stats stats;
  661. Event event;
  662. LifeCycleFunctor functor(&stats, &event);
  663. background_thread->PostTask(RTC_FROM_HERE, functor);
  664. event.Wait(Event::kForever);
  665. EXPECT_EQ(1u, stats.copy_count);
  666. EXPECT_EQ(0u, stats.move_count);
  667. }
  668. TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
  669. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  670. background_thread->Start();
  671. LifeCycleFunctor::Stats stats;
  672. Event event;
  673. LifeCycleFunctor functor(&stats, &event);
  674. background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
  675. event.Wait(Event::kForever);
  676. EXPECT_EQ(0u, stats.copy_count);
  677. EXPECT_EQ(1u, stats.move_count);
  678. }
  679. TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
  680. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  681. background_thread->Start();
  682. LifeCycleFunctor::Stats stats;
  683. Event event;
  684. LifeCycleFunctor functor(&stats, &event);
  685. LifeCycleFunctor& functor_ref = functor;
  686. background_thread->PostTask(RTC_FROM_HERE, functor_ref);
  687. event.Wait(Event::kForever);
  688. EXPECT_EQ(1u, stats.copy_count);
  689. EXPECT_EQ(0u, stats.move_count);
  690. }
  691. TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
  692. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  693. background_thread->Start();
  694. Event event;
  695. bool was_invoked_on_background_thread = false;
  696. DestructionFunctor functor(background_thread.get(),
  697. &was_invoked_on_background_thread, &event);
  698. background_thread->PostTask(RTC_FROM_HERE, functor);
  699. event.Wait(Event::kForever);
  700. EXPECT_TRUE(was_invoked_on_background_thread);
  701. }
  702. TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
  703. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  704. background_thread->Start();
  705. Event event;
  706. bool was_invoked_on_background_thread = false;
  707. DestructionFunctor functor(background_thread.get(),
  708. &was_invoked_on_background_thread, &event);
  709. background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
  710. event.Wait(Event::kForever);
  711. EXPECT_TRUE(was_invoked_on_background_thread);
  712. }
  713. TEST(ThreadPostTaskTest,
  714. InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
  715. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  716. background_thread->Start();
  717. Event event;
  718. bool was_invoked_on_background_thread = false;
  719. DestructionFunctor functor(background_thread.get(),
  720. &was_invoked_on_background_thread, &event);
  721. DestructionFunctor& functor_ref = functor;
  722. background_thread->PostTask(RTC_FROM_HERE, functor_ref);
  723. event.Wait(Event::kForever);
  724. EXPECT_TRUE(was_invoked_on_background_thread);
  725. }
  726. TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
  727. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  728. background_thread->Start();
  729. Event event;
  730. bool was_invoked_on_background_thread = false;
  731. background_thread->PostTask(RTC_FROM_HERE,
  732. Bind(&ThreadIsCurrent, background_thread.get(),
  733. &was_invoked_on_background_thread, &event));
  734. event.Wait(Event::kForever);
  735. EXPECT_TRUE(was_invoked_on_background_thread);
  736. }
  737. TEST(ThreadPostTaskTest, InvokesAsynchronously) {
  738. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  739. background_thread->Start();
  740. // The first event ensures that SendSingleMessage() is not blocking this
  741. // thread. The second event ensures that the message is processed.
  742. Event event_set_by_test_thread;
  743. Event event_set_by_background_thread;
  744. background_thread->PostTask(RTC_FROM_HERE,
  745. Bind(&WaitAndSetEvent, &event_set_by_test_thread,
  746. &event_set_by_background_thread));
  747. event_set_by_test_thread.Set();
  748. event_set_by_background_thread.Wait(Event::kForever);
  749. }
  750. TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
  751. std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
  752. background_thread->Start();
  753. Event first;
  754. Event second;
  755. Event third;
  756. Event fourth;
  757. background_thread->PostTask(RTC_FROM_HERE,
  758. Bind(&WaitAndSetEvent, &first, &second));
  759. background_thread->PostTask(RTC_FROM_HERE,
  760. Bind(&WaitAndSetEvent, &second, &third));
  761. background_thread->PostTask(RTC_FROM_HERE,
  762. Bind(&WaitAndSetEvent, &third, &fourth));
  763. // All tasks have been posted before the first one is unblocked.
  764. first.Set();
  765. // Only if the chain is invoked in posted order will the last event be set.
  766. fourth.Wait(Event::kForever);
  767. }
  768. } // namespace
  769. } // namespace rtc