Reputation: 2180
I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work. The intent is to pass 10 objects from the produce to the consumer. Unfortunately, I'm running into compilation issues. Does anyone know where I have gone wrong? Thank you!
Update solution.
#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdlib.h>
#include <future>
#include <functional>
#include <vector>
using namespace std;
using namespace std::chrono;
struct MSG {
int val;
};
void consumer(vector<future<MSG>> *futv) {
for (auto& p : *futv) {
this_thread::sleep_for(milliseconds{rand() % 25});
MSG m = p.get();
cout << m.val << endl;
}
}
void producer(vector<promise<MSG>> *promv) {
MSG m = {0};
for (auto& p : *promv) {
this_thread::sleep_for(milliseconds{rand() % 25});
p.set_value(m);
m.val++;
}
}
int main(int argc, char *argv[])
{
vector<promise<MSG>> promv;
vector<future<MSG>> futv;
for (int i=0; i<10; i++) {
promv.push_back(promise<MSG>());
futv.push_back(promv[i].get_future());
}
thread tp {producer, &promv};
thread tc {consumer, &futv};
tp.join();
tc.join();
return 0;
}
Compilation...,
g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9
Upvotes: 0
Views: 747
Reputation: 181
You can use condition_variable
, it is well placed than future/promise implementations in this case.
For example, taking two threads, product and consumer, when the product 'i' (product element) is finished, it will be passed on to a consumer 'i' who waits until the product is ready and is consumed afterwards.
future/promise is used, for instance, for multiple return value threads.
If you want your thread to return multiple values at different point of time then just pass multiple std::promise objects in thread and fetch multiple return values from thier associated multiple std::future objects.
Upvotes: 0
Reputation: 13634
The error is due to future
being only movable but not copyable
for (auto p : futv)
- this is an attempt to copy elements fro vector.
Use the following loops to have reference to vector element instead:
for (auto& p : futv)
or
for (decltype(auto) p : futv)
Generally the idea may work as an exercise, but promises/futures are not really designed for that. The problem is that you cannot reuse elements of your array for another run. So for real uses, producer-consumer queues are implemented by using lower level primitives: mutexes, condition variables, atomics, etc.
Upvotes: 2