daily pastebin goal
19%
SHARE
TWEET

Untitled

a guest Sep 25th, 2018 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <cmath>
  3. #include <thread>
  4. #include <future>
  5. #include <vector>
  6. #include <mutex>
  7. #include <atomic>
  8.  
  9. using namespace std;
  10.  
  11. using promises = vector<pair<promise<bool>, int>>;
  12.  
  13. promises v;
  14. mutex m;
  15. atomic<int> counter;
  16.  
  17. void put_value(promises* v) {
  18.     auto x = rand()%100;
  19.     promise<bool> promiseObj;
  20.     auto future = promiseObj.get_future();
  21.     m.lock();
  22.     v->push_back({move(promiseObj), x});
  23.     m.unlock();
  24.     counter++;
  25.     auto y = future.get();
  26.     m.lock();
  27.     cout << x << ", " << y << endl;
  28.     m.unlock();
  29. };
  30.  
  31. bool is_prime(int x) {
  32.     for(auto i = 2; i <= sqrt(x); ++i) {
  33.         if (!(x%i)) {
  34.             return false;
  35.         }
  36.     }
  37.     return true;
  38. };
  39.  
  40. void map(promises* v) {
  41.     while(counter < 10);
  42.     for(auto& p: *v) {
  43.         p.first.set_value(is_prime(p.second));
  44.     }
  45. };
  46.  
  47. int main() {
  48.     thread ts[10];
  49.     thread m{map, &v};
  50.     for(auto& t: ts) {
  51.         t = thread{put_value, &v};
  52.     }
  53.     for(auto& t: ts) {
  54.         t.join();
  55.     }
  56.     m.join();
  57. }
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