Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <sched.h>
- #include <signal.h>
- #include <functional>
- #include <sys/types.h>
- #include <sys/wait.h>
- #define STACK_SIZE 1024 * 10
- #define CHECK(fun) \
- if ((fun) == -1) { \
- throw std::system_error(errno, std::generic_category()); \
- }
- int threadHelper(void *ptr) {
- auto *fn = static_cast<std::function<int()> *>(ptr);
- (*fn)();
- return 0;
- }
- class myThread{
- public:
- myThread(){
- pid = NULL;
- stack = nullptr;
- };
- myThread(int (*fn)(void*)){
- stack = new char[STACK_SIZE];
- CHECK(pid = clone(fn, stack + STACK_SIZE, CLONE_VM | SIGCHLD, nullptr));
- }
- myThread(std::function<int()> &&fn) {
- stack = new char[STACK_SIZE];
- CHECK(pid = clone(threadHelper, stack + STACK_SIZE, CLONE_VM | SIGCHLD, &fn));
- }
- pid_t get_id() { return pid; }
- ~myThread(){
- if (pid != NULL) {
- kill(pid, SIGTERM);
- }
- delete[] stack;
- }
- myThread &operator=(myThread&& other){
- this->swap(other);
- return *this;
- }
- void swap(myThread& other){
- std::swap(this->pid, other.pid);
- std::swap(this->stack, other.stack);
- }
- bool joinable() {
- return pid != 0;
- }
- void join() {
- waitpid(pid, NULL, 0);
- kill(pid, SIGTERM);
- pid = NULL;
- }
- private:
- int pid;
- char *stack;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement