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

标签 c++ multithreading sockets ssl future

我正在创建 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/

相关文章:

c++ - qtextedit - 调整大小以适应

c++ - Speex AEC 仅去除一部分回声

python - 多进程池与 asyncio.run_in_executor

java - 何时调用Object.wait

c - 使用 listen(1) 的套接字上的两个(错误的)连接

c++ - 我想在迭代时对 std::map 执行就地修改

multithreading - 我们可以在多核CPU中的特定内核上运行linux内核吗?

android - 使用套接字时避免垃圾收集

mysql - 第 15 行第 2 列语法错误 : ` socket:/tmp/mysql.sock'

C++如何从文件中读取 float 并将其存储到另一个文件中?