Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #pragma once
  2. #include <sched.h>
  3. #include <signal.h>
  4. #include <functional>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7.  
  8. #define STACK_SIZE 1024 * 10
  9.  
  10. #define CHECK(fun) \
  11.     if ((fun) == -1) { \
  12.         throw std::system_error(errno, std::generic_category()); \
  13.     }
  14.  
  15. int threadHelper(void *ptr) {
  16.     auto *fn = static_cast<std::function<int()> *>(ptr);
  17.     (*fn)();
  18.     return 0;
  19. }
  20.  
  21. class myThread{
  22. public:
  23.     myThread(){
  24.         pid = NULL;
  25.         stack = nullptr;
  26.     };
  27.  
  28.     myThread(int (*fn)(void*)){
  29.         stack = new char[STACK_SIZE];
  30.         CHECK(pid = clone(fn, stack + STACK_SIZE, CLONE_VM | SIGCHLD, nullptr));                                   
  31.     }
  32.  
  33.     myThread(std::function<int()> &&fn) {
  34.         stack = new char[STACK_SIZE];
  35.         CHECK(pid = clone(threadHelper, stack + STACK_SIZE, CLONE_VM | SIGCHLD, &fn));
  36.     }
  37.  
  38.     pid_t get_id() { return pid; }
  39.  
  40.  
  41.     ~myThread(){
  42.         if (pid != NULL) {
  43.             kill(pid, SIGTERM);
  44.         }
  45.         delete[] stack;
  46.     }
  47.  
  48.     myThread &operator=(myThread&& other){
  49.         this->swap(other);
  50.         return *this;
  51.     }
  52.  
  53.     void swap(myThread& other){
  54.         std::swap(this->pid, other.pid);
  55.         std::swap(this->stack, other.stack);
  56.     }
  57.  
  58.     bool joinable() {
  59.         return pid != 0;
  60.     }
  61.  
  62.     void join() {
  63.         waitpid(pid, NULL, 0);
  64.         kill(pid, SIGTERM);
  65.         pid = NULL;
  66.     }
  67.  
  68. private:
  69.     int pid;
  70.     char *stack;
  71. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement