Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <queue>
  5. #include <random>
  6.  
  7. class HelloFunctionObject {
  8.     bool stop;
  9.     std::mutex& mutex;
  10. public:
  11.  
  12.     HelloFunctionObject(std::mutex& mutex) :stop(false), mutex(mutex) {}
  13.     void operator()() const {
  14.         std::cout << "Hello C++11 from a function object." << std::endl;
  15.         while(getStop());
  16.         std::cout << "Stop C++11 from a function object." << std::endl;
  17.     }
  18.  
  19.     void setStop(const bool stop) {
  20.         mutex.lock();
  21.         this->stop = stop;
  22.         mutex.unlock();
  23.     }
  24.     bool getStop() const {
  25.         mutex.lock();
  26.         bool rt = stop;
  27.         mutex.unlock();
  28.         return rt;
  29.     }
  30. };
  31.  
  32. class AsynchroniousQueue {
  33. private:
  34.     std::queue<int> queue_;
  35.     std::mutex block;
  36. public:
  37.     AsynchroniousQueue();
  38.     void push(const int element);
  39.     int pop();
  40.     size_t size();
  41. };
  42.  
  43. AsynchroniousQueue::AsynchroniousQueue() : block() {}
  44.  
  45. void AsynchroniousQueue::push(const int element) {
  46.     block.lock();
  47.     queue_.push(element);
  48.     block.unlock();
  49. }
  50.  
  51. int AsynchroniousQueue::pop() {
  52.     block.lock();
  53.     int rt = queue_.front();
  54.     queue_.pop();
  55.     block.unlock();
  56.     return rt;
  57. }
  58.  
  59. size_t AsynchroniousQueue::size()
  60. {
  61.     block.lock();
  62.     size_t rt = queue_.size();
  63.     block.unlock();
  64.     return rt;
  65. }
  66.  
  67. int randomInt(int min, int max) {
  68.     static std::random_device rd;
  69.     std::uniform_int_distribution<int> d(min, max);
  70.     return d(rd);
  71. }
  72.  
  73.  
  74. void asQue(AsynchroniousQueue& queue) {
  75.     for(int i = 0; i < pow(1000, 3); i++) {
  76.         queue.push(randomInt(1, 20));
  77.     }
  78. }
  79.  
  80. int main() {
  81.     /*std::mutex mutex;
  82.     HelloFunctionObject hello_function(mutex);
  83.     std::thread t2(hello_function);
  84.  
  85.     hello_function.setStop(true);
  86.  
  87.     t2.join();
  88. */
  89.  
  90.     AsynchroniousQueue queue;
  91.  
  92.     std::thread t1(asQue, queue), t2(asQue, queue);
  93.  
  94.     t1.join();
  95.     t2.join();
  96.  
  97.     std::cout << queue.size() << std::endl;
  98.     std::cout << std::endl;
  99.  
  100.     std::cin.clear();
  101.     std::cin.ignore(2);
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement