Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. //main.cpp
  2. int main() {
  3.     Home* homePtr = new Home();
  4.     std::mutex* catMutexPtr = new std::mutex;
  5.    
  6.     Cat pepper = Cat("Pepper", breeds::mongrel, homePtr, catMutexPtr);
  7.    
  8.     // delete homePtr;
  9.     // delete catMutexPtr;
  10.    
  11.     pepper.thread_.join();
  12.     return 0;
  13. }
  14.  
  15. //cats.cpp
  16. Cat::Cat(std::string name, breeds breed, Home* homePtr, std::mutex* catMutexPtr) {
  17.     name_ = name;
  18.     breed_ = breed;
  19.     homePtr_ = homePtr;
  20.     catMutexPtr_ = catMutexPtr;
  21.     inHome = false;
  22.    
  23.     thread_ = std::thread(&Cat::beingACat, this);
  24. }
  25.  
  26. void Cat::beingACat() {
  27.     while(true) {
  28.         if(inHome == false) {
  29.             if( rand() % 100 < 1) {
  30.                 catMutexPtr_->lock();
  31.                 goToHome();
  32.                 catMutexPtr_->unlock();
  33.             } else {
  34.                 std::this_thread::sleep_for(std::chrono::milliseconds(1));
  35.             }
  36.         } else {
  37.             if( rand() % 100 < 5) {
  38.                 catMutexPtr_->lock();
  39.                 goOutside();
  40.                 catMutexPtr_->unlock();
  41.             }
  42.             else {
  43.                 std::this_thread::sleep_for(std::chrono::milliseconds(1));
  44.             }
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement