Implementar operaciones asincrónicas largas de forma síncrona

I need to implement function which involves long async operation (send request to external server and periodically check if it is done) which needs to behave like synchronous operation. I'm doing that following way:

while True:
  if operation_finished():

I wonder if this is a acceptable and if there is better solution?

preguntado el 08 de noviembre de 11 a las 18:11

Don't really understand why you'd use while True: con un separado if instead of just putting the condition in the while loop, but other than that, it looks fine. -

2 Respuestas

Depending on the nature of the asynchronous operation, there are various existing solutions which will allow you to do this more elegantly. For example, if you're waiting for a response from a server, you can use seleccione on the socket to wait for a reply. You can also do this on several sockets at once.

Note: You should always use a timeout when possible to avoid waiting forever in case of some kind of error. The loop mentioned in your post suffers from this as well -- you should limit the total time or the number of iterations.

respondido 08 nov., 11:23

You would really prefer to stay away from polling. Synchronous operations will scale better and be easier to debug. If you have control over the external protocol then make it sync. I say this mostly because I think a lot of people make things async thinking that somehow improves performance when it really just makes things more difficult.

You can then make sync operations appear async to your local event loop using multiple threads of control (threads, processes, select based FSMs, whatever). If you don't have control over the external protocol and it is really async then you have no choice but to poll. Depending on what you think the distribution of response times will be I'd use some sort of exponential backoff with a cap for the poll period. For most programs I'd have that external to my main event loop and have it report back via some event mechanism to my event loop.

respondido 09 nov., 11:00

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.