Btk
thread.hpp
1 #if !defined(_BTK_IMPL_THREAD_HPP_)
2 #define _BTK_IMPL_THREAD_HPP_
3 #include <SDL2/SDL_thread.h>
4 #include <SDL2/SDL_mutex.h>
5 #include <memory>
6 #include <tuple>
7 
8 #include "../exception.hpp"
9 namespace Btk{
10  //SDL_Thread
11  namespace Impl{
12  template<class T,class ...Args>
13  struct ThreadInvoker{
14  T callable;
15  std::tuple<Args...> args;
16  //A Simple invoker for SDL_Thread
17  static int SDLCALL Run(void *__self){
18  std::unique_ptr<ThreadInvoker> ptr(static_cast<ThreadInvoker*>(__self));
19  std::apply(ptr->callable,ptr->args);
20  return 0;
21  }
22  };
23  };
24  class Thread{
25  public:
34  template<class Callable,class ...Args>
35  Thread(Callable &&callable,Args ...args){
36  using InvokerType = Impl::ThreadInvoker
37  <std::remove_reference_t<Callable>,Args...>;
38 
39 
40  auto *invoker = new InvokerType{
41  std::forward<Callable>(callable),
42  {std::forward<Args>(args)...}
43  };
44  thrd = SDL_CreateThread(
45  InvokerType::Run,
46  nullptr,
47  invoker
48  );
49  };
50  template<class Callable,class ...Args>
51  Thread(const char *name,Callable &&callable,Args ...args){
52  using InvokerType = Impl::ThreadInvoker
53  <std::remove_reference_t<Callable>,Args...>;
54 
55 
56  auto *invoker = new InvokerType{
57  std::forward<Callable>(callable),
58  {std::forward<Args>(args)...}
59  };
60  thrd = SDL_CreateThread(
61  InvokerType::Run,
62  name,
63  invoker
64  );
65  };
66  Thread():thrd(nullptr){};
67  Thread(const Thread &) = delete;
68  Thread(Thread &&t):thrd(t.thrd){
69  t.thrd = nullptr;
70  };
71  ~Thread(){
72  //Default to wait thread
73  SDL_WaitThread(thrd,nullptr);
74  };
75 
76 
77  //methods
78  void wait(){
79  SDL_WaitThread(thrd,nullptr);
80  thrd = nullptr;
81  };
82  void join(){
83  wait();
84  };
85  void detach(){
86  SDL_DetachThread(thrd);
87  thrd = nullptr;
88  };
89 
90  Thread &operator =(Thread &&th){
91  thrd = th.thrd;
92  th.thrd = nullptr;
93  return *this;
94  };
95  private:
96  SDL_Thread *thrd;
97  };
98  class SpinLock{
99  public:
100  void lock() noexcept{
101  SDL_AtomicLock(&slock);
102  };
103  void unlock() noexcept{
104  SDL_AtomicUnlock(&slock);
105  };
106  bool try_lock() noexcept{
107  return SDL_AtomicTryLock(&slock);
108  };
109  private:
110  SDL_SpinLock slock = 0;
111  };
112 };
113 
114 
115 #endif // _BTK_IMPL_THREAD_HPP_
Definition: thread.hpp:24
This header include many useful containers.
Definition: async.hpp:7
Definition: thread.hpp:98
Thread(Callable &&callable, Args ...args)
Construct a new Thread object.
Definition: thread.hpp:35
Definition: thread.hpp:13