首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于令牌的同步阻塞队列

基于令牌的同步阻塞队列
EN

Software Engineering用户
提问于 2016-02-25 09:39:57
回答 1查看 174关注 0票数 0

我目前正在为C++中的以下用例寻找一个很好的解决方案(最好是C++11或C++14):

该程序正在运行一个具有TCP连接的服务器。其他客户端可以随时连接到此服务器并触发计算(这需要几秒钟)。一次只能运行一次计算。其他计算调用应该排队,并阻止它们的调用,直到结果就绪。如果当前计算失败,则不应立即执行所有其他计算并返回。

下面是一些描述步骤的示例代码:

代码语言:javascript
复制
// 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::promisestd::future:当请求出现时,future被添加到队列中,调用等待未来。当上一次计算完成时,它使用允诺通知下一个调用方。你能想出更好的解决方案吗?

EN

回答 1

Software Engineering用户

回答已采纳

发布于 2016-02-25 19:26:48

我会在后端处理一些事情,而不是额外的令牌之类的。换句话说,当请求传入时,总是将其推入队列。

后端(从队列中提取请求的部分)只需提取项并执行计算。当/如果发生故障时,它只设置一个failed标志,从那时起,它返回false (或者它需要做的任何事情来发出故障信号)。

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Software Engineering提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://softwareengineering.stackexchange.com/questions/311057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档