SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <future>
  3. #include <mutex>
  4. #include <thread>
  5. #include <vector>
  6. #include <string>
  7. #include <sstream>
  8. #include <random>
  9. #include "exchanger.cpp"
  10.  
  11. class thread_guard {
  12. private:
  13.     std::thread& t;
  14. public:
  15.     explicit thread_guard(std::thread& t) : t(t){}
  16.    
  17.     ~thread_guard(){
  18.         if (t.joinable()){
  19.             t.join();
  20.         }
  21.     }
  22.    
  23.     thread_guard(thread_guard const&)=delete;
  24.     thread_guard& operator=(thread_guard const&) = delete;
  25. };
  26.  
  27. class threads_guard {
  28. private:
  29.     std::vector<thread_guard*> threads;
  30. public:
  31.     explicit threads_guard(){}
  32.    
  33.     ~threads_guard(){
  34.         for (auto p : threads)
  35.             delete p;
  36.     }
  37.    
  38.     void add(std::thread& t){
  39.         thread_guard* tg = new thread_guard(t);
  40.         threads.push_back(tg);
  41.     }
  42. };
  43.  
  44. int random_number(){
  45.     std::random_device dev;
  46.     std::mt19937 rng(dev());
  47.     std::uniform_int_distribution<std::mt19937::result_type> dist(1,5000);
  48.    
  49.     return dist(rng);
  50. }
  51.  
  52. void rand_wait(){
  53.     int x = random_number();
  54.     std::this_thread::sleep_for(std::chrono::milliseconds(x));
  55.     std::cout << "process ended, waited " << x << " milliseconds" << std::endl;
  56. }
  57.  
  58. int main(){
  59.     threads_guard t{};
  60.    
  61.     for(int x=0;x<100;x++){
  62.         auto t1 = new std::thread(rand_wait);
  63.         t.add(*t1);
  64.     }
  65. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top