Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <time.h>
  5. std::mutex mtx;
  6.  
  7. class Sandeliai{
  8.     int A;
  9.     int B;
  10.     public:
  11.         Sandeliai():
  12.         A(50), B(50){
  13.             std::cout<<"pries pervezima: ";    
  14.             print();
  15.         }
  16.         Sandeliai(int a, int b):
  17.         A(a), B(b){  
  18.             std::cout<<"pries pervezima: ";
  19.             print();
  20.             }
  21.         void A_i_B(){
  22.             for(int i=0; i<10000; i++){
  23.                 int move = rand() % 100000 +1;
  24.                 if(A>=move){
  25.                     mtx.lock();
  26.                     A-=move;
  27.                     B+=move;
  28.                     mtx.unlock();
  29.                 }
  30.             }
  31.         }
  32.         void B_i_A(){
  33.             for(int i=0; i<10000; i++){
  34.                 int move = rand() % 100000 +1;
  35.                 if(B>=move){
  36.                     mtx.lock();
  37.                     B-=move;
  38.                     A+=move;
  39.                     mtx.unlock();
  40.                 }
  41.             }
  42.         }
  43.         void print(){
  44.             std::cout<<"A: "<<A<<" B: "<<B<<" suma: "<<A+B<<std::endl;
  45.         }
  46. };
  47. int main(){
  48.     srand(time(NULL));
  49.     std::thread workers[200];
  50.     Sandeliai* sandelys = new Sandeliai(4000000,4000000);
  51.     for(int i=0; i < 200; i++){
  52.         if(i <100){
  53.             workers[i] = std::thread(&Sandeliai::A_i_B, sandelys);
  54.         }
  55.         else{
  56.             workers[i] = std::thread(&Sandeliai::B_i_A, sandelys);
  57.         }
  58.     }
  59.     for(int i = 0; i < 200; i++){
  60.         workers[i].join();
  61.     }
  62.     /*
  63.     std::thread worker(&Sandeliai::A_i_B, sandelys);
  64.     std::thread worker2(&Sandeliai::B_i_A, sandelys);
  65.     worker.join();
  66.     worker2.join();
  67.     */
  68.  
  69.     std::cout<<"po pervezimo: ";
  70.     sandelys->print();
  71.     return 0;
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement