简体   繁体   中英

std::future.wait_for blocking forever

I am crating SSL socket and when I try to connect to that socket my program hangs.

I found some issue that server does not send any data so SSL connection is waiting for the any response.

I decided to create future and kill it after timeout. But it is still hanging.

If you see to the code, below part is not executed: 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";

To simulate stopping response from server I just run:

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

How do I kill the SSL connection? I want to continue execution of code after kill the future.

EDIT: I do not want to open another question for that. Answer : So i am sure now that this is because of future destructor. It is waiting for finish of code from the future body.

Question 2: How Can I fix above issue? I want to execute code after scope which future is in.

Is it OK to create thread and wait until timeout or ssl some mutex is unlocked?

The problem with your code is that when the future goes out of scope, its destructor might block as reported in the documentation for std::future<T>::~future :

It says explicitly:

... 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.

In your case:

  1. the shared state is not yet ready: SSL hangs forever
  2. that is the only (and so last) reference to the shared state.

The solution to your problem is that you have to make the scope of variable std::future<void> future such that it outlives the part of the code you want not to be blocked.

Check these answers:

LIVE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM