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:
start_long_operation() while True: if operation_finished(): return sleep()
I wonder if this is a acceptable and if there is better solution?
preguntado el 08 de noviembre de 11 a las 18:11
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.
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.