我目前正在为C++中的以下用例寻找一个很好的解决方案(最好是C++11或C++14):
该程序正在运行一个具有TCP连接的服务器。其他客户端可以随时连接到此服务器并触发计算(这需要几秒钟)。一次只能运行一次计算。其他计算调用应该排队,并阻止它们的调用,直到结果就绪。如果当前计算失败,则不应立即执行所有其他计算并返回。
下面是一些描述步骤的示例代码:
// the first client calling this function should get the token,
// all others have to wait until first one finished.
// Then the next in the queue can continue
bool gotCalculateRequest() {
// blocks until currently running calulation finished.
// If getToken returns false, do not queue this request for calculation
if (!getToken()) {
// notify client that calculation was aborted
return false;
}
// now we have the token and we can start calculation
if (!doStuff()) {
// give back the token and abort other requests in the queue
freeTokenAndAbortOthers();
return false;
}
// give back the token. This should automatically notify the next waiting request to continue
freeToken();
return true;
}为此,我考虑使用std::promise和std::future:当请求出现时,future被添加到队列中,调用等待未来。当上一次计算完成时,它使用允诺通知下一个调用方。你能想出更好的解决方案吗?
发布于 2016-02-25 19:26:48
我会在后端处理一些事情,而不是额外的令牌之类的。换句话说,当请求传入时,总是将其推入队列。
后端(从队列中提取请求的部分)只需提取项并执行计算。当/如果发生故障时,它只设置一个failed标志,从那时起,它返回false (或者它需要做的任何事情来发出故障信号)。
bool do_calculation(calc_spec const &input, result_type &output) {
static bool failed;
if (failed)
return false;
output = calculation_impl(input);
if (calc_failed(output)) {
failed = true;
return false;
}
return true;
}https://softwareengineering.stackexchange.com/questions/311057
复制相似问题