kodi
TestHelpers.h
1 /*
2  * Copyright (C) 2005-2018 Team Kodi
3  * This file is part of Kodi - https://kodi.tv
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  * See LICENSES/README.md for more information.
7  */
8 
9 #pragma once
10 
11 #include "threads/Thread.h"
12 
13 #include <memory>
14 #include <mutex>
15 
16 #include <gtest/gtest.h>
17 
18 template<class E>
19 inline static bool waitForWaiters(E& event, int numWaiters, std::chrono::milliseconds duration)
20 {
21  for (auto i = std::chrono::milliseconds::zero(); i < duration; i++)
22  {
23  if (event.getNumWaits() == numWaiters)
24  return true;
25 
26  std::this_thread::sleep_for(std::chrono::milliseconds(1));
27  }
28 
29  return false;
30 }
31 
32 inline static bool waitForThread(std::atomic<long>& mutex,
33  int numWaiters,
34  std::chrono::milliseconds duration)
35 {
36  CCriticalSection sec;
37  for (auto i = std::chrono::milliseconds::zero(); i < duration; i++)
38  {
39  if (mutex == (long)numWaiters)
40  return true;
41 
42  {
43  std::unique_lock<CCriticalSection> tmplock(sec); // kick any memory syncs
44  }
45 
46  std::this_thread::sleep_for(std::chrono::milliseconds(1));
47  }
48 
49  return false;
50 }
51 
53 {
54  std::atomic<long>* val;
55 public:
56  inline AtomicGuard(std::atomic<long>* val_) : val(val_) { if (val) ++(*val); }
57  inline ~AtomicGuard() { if (val) --(*val); }
58 };
59 
60 class thread
61 {
62  std::unique_ptr<CThread> cthread;
63 
64 public:
65  inline explicit thread(IRunnable& runnable)
66  : cthread(std::make_unique<CThread>(&runnable, "DumbThread"))
67  {
68  cthread->Create();
69  }
70 
71  void join() { cthread->Join(std::chrono::milliseconds::max()); }
72 
73  bool timed_join(std::chrono::milliseconds duration) { return cthread->Join(duration); }
74 };
75 
Definition: TestHelpers.h:60
Definition: IRunnable.h:11
Definition: TestHelpers.h:52