gpt4 book ai didi

C++类中的C++过期机制

转载 作者:行者123 更新时间:2023-11-28 05:20:23 25 4
gpt4 key购买 nike

我们有一个新的要求使用授权来调用http服务 token 。因此,为了获得“结果”,我们需要分两步进行。首先进行 http 调用以从 auth 服务器获取授权 token 然后使用 token 制作第二个 http 以获得“结果”(通过 header 中的身份验证 token )。

我们需要 boost 这个“简单”的两个 http 调用模型,因为我们可以重用授权 token 一段时间,例如 5 分钟。所以我们可以调用授权服务器获取 token 并在 5 分钟内更新 token ,依此类推。

我们希望在一个 C++ 类中拥有它,所以从我们的 main 函数中执行此操作

//main.cpp

Authorization auth_obj; //global
int main(...)
{
auth_obj::initialize(); //call a static function

process_loop(); //for ever
}

process_loop() {

select(...) {
details = auth_obj->get_auth_details();

http->add_header(details);
"result" = http->getResult();

}

}

//Authorization.cpp

class Authorization {

details_t auth_details_;
get_auth_details( return auth_details_;)
initialize(){

auth_details = http->get_token_from_server();
save(auth_details)
renew(5 minutes);
}

save(auth_details) { auth_details = auth_details}

renew(time argument) {
//blocks here for 5 minutes
}
}

上面这段伪代码的问题在于,当我们调用初始化时,执行将阻塞在 Authorization::renew(...) 中。

我们需要调用初始化,获取第一个 token ,5 分钟后授权类实例自动更新 token 并等待接下来的 5 分钟,依此类推。

执行此操作的正确方法是什么? boost::异步, boost::线程,标准::线程?有没有例子?

最佳答案

对于您想要实现的目标,有两种方法。

  1. 如果你不想涉及多线程。您可以在 Authorization 类中添加一个 Timer,计时器将在 5 分钟后到期,在发送您的请求之前检查 token 是否过期。
  2. 使用另一个线程每 5 分钟更新一次 token 。在这种情况下,您可以使用 std::thread 并创建您的线程来像这样更新 token :

    class Authorization
    {
    public:
    Authorization() = default;
    ~Authorization()
    {
    token_update_thread.detach();
    }

    details_t get_auth_details()
    {
    std::lock_guard<std::mutex> lock(token_lock);
    return auth_details_;
    }

    void initialize()
    {
    token_update_thread = std::move(std::thread([this]()
    {
    while (true) {
    renew();
    std::this_thread::sleep_for(
    std::chrono::minutes(5));
    }
    }));
    }

    void renew()
    {
    std::lock_guard<std::mutex> lock(token_lock);
    // do whatever you need to update auth_details_
    }

    std::mutex token_lock;
    details_t auth_details_;
    std::thread token_update_thread;
    };

关于C++类中的C++过期机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41651992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com