Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <future>
- #include <mutex>
- #include <thread>
- #include <vector>
- #include <string>
- #include <sstream>
- #include <random>
- #include "exchanger.cpp"
- class thread_guard {
- private:
- std::thread& t;
- public:
- explicit thread_guard(std::thread& t) : t(t){}
- ~thread_guard(){
- if (t.joinable()){
- t.join();
- }
- }
- thread_guard(thread_guard const&)=delete;
- thread_guard& operator=(thread_guard const&) = delete;
- };
- class threads_guard {
- private:
- std::vector<thread_guard*> threads;
- public:
- explicit threads_guard(){}
- ~threads_guard(){
- for (auto p : threads)
- delete p;
- }
- void add(std::thread& t){
- thread_guard* tg = new thread_guard(t);
- threads.push_back(tg);
- }
- };
- int random_number(){
- std::random_device dev;
- std::mt19937 rng(dev());
- std::uniform_int_distribution<std::mt19937::result_type> dist(1,5000);
- return dist(rng);
- }
- void rand_wait(){
- int x = random_number();
- std::this_thread::sleep_for(std::chrono::milliseconds(x));
- std::cout << "process ended, waited " << x << " milliseconds" << std::endl;
- }
- int main(){
- threads_guard t{};
- for(int x=0;x<100;x++){
- auto t1 = new std::thread(rand_wait);
- t.add(*t1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement