Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <thread>
- #include <future>
- #include <vector>
- #include <mutex>
- #include <atomic>
- using namespace std;
- using promises = vector<pair<promise<bool>, int>>;
- promises v;
- mutex m;
- atomic<int> counter;
- void put_value(promises* v) {
- auto x = rand()%100;
- promise<bool> promiseObj;
- auto future = promiseObj.get_future();
- m.lock();
- v->push_back({move(promiseObj), x});
- m.unlock();
- counter++;
- auto y = future.get();
- m.lock();
- cout << x << ", " << y << endl;
- m.unlock();
- };
- bool is_prime(int x) {
- for(auto i = 2; i <= sqrt(x); ++i) {
- if (!(x%i)) {
- return false;
- }
- }
- return true;
- };
- void map(promises* v) {
- while(counter < 10);
- for(auto& p: *v) {
- p.first.set_value(is_prime(p.second));
- }
- };
- int main() {
- thread ts[10];
- thread m{map, &v};
- for(auto& t: ts) {
- t = thread{put_value, &v};
- }
- for(auto& t: ts) {
- t.join();
- }
- m.join();
- }
Add Comment
Please, Sign In to add comment