gpt4 book ai didi

c++ - std::future.wait_for 永远阻塞

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:25 25 4
gpt4 key购买 nike

我正在创建 SSL 套接字,当我尝试连接到该套接字时,我的程序挂起。

我发现一些问题,服务器不发送任何数据,因此 SSL 连接正在等待任何响应。

我决定创建 future 并在超时后将其杀死。但它仍然挂着。

如果您查看代码,下面的部分不会执行:cout<<"TEST";

{

std::future<void> future = std::async(std::launch::async,
[&](){
err = SSL_connect (m_ssl);
});

std::future_status status;
status = future.wait_for(std::chrono::seconds(t_timeout));
}

cout<<"TEST";

为了模拟来自服务器的停止响应,我刚刚运行:

for item in $(seq 1 1000); do sudo nc -i 100000ms -l 443 >> log.out; done;

如何终止 SSL 连接?我想在杀死 future 后继续执行代码。

编辑:我不想为此提出另一个问题。回答:所以我现在确定这是因为 future 的析构函数。它正在等待来自 future 主体的代码完成。

问题 2:我该如何解决上述问题?我想在 future 所在的范围之后执行代码。

是否可以创建线程并等待超时或 ssl 某些互斥体被解锁?

最佳答案

您的代码的问题在于,当 future 超出范围时,它的析构函数可能会阻塞,如 documentation 中所报告的那样对于 std::future<T>::~future :

它明确地说:

... will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

在你的情况下:

  1. 共享状态尚未就绪:SSL 永远挂起
  2. 这是对共享状态的唯一(也是最后一个)引用。

您的问题的解决方案是您必须使变量的范围为 std::future<void> future这样它就比您不希望被阻止的代码部分长。

检查这些答案:

LIVE DEMO

关于c++ - std::future.wait_for 永远阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291078/

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