【发布时间】:2020-05-28 18:38:20
【问题描述】:
我正在尝试编写一个简单的程序来通过 future 和 promise 传递消息,所以我了解它们是如何工作的。目的是将 10 个对象从产品传递给消费者。不幸的是,我遇到了编译问题。有谁知道我哪里出错了? 谢谢!
更新解决方案。
#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;
}
编译...,
g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9
【问题讨论】:
-
你不能重用一个承诺。你只能通过 Promise 发送一个值。