I have the following method concurrent_api_call_and_processing() that takes below parameters:
- api_call: is an HTTP request to an external WebSite that retrieve and XLM document
- lst: is a list of integers(ids) needed by api_call
- callback_processing: Is a local method that just parses each XLM request
I do around 500 HTTP requests , one for each id in lst, using api_call() Then each response if processed with the local method callback_processing() that parse the XLM and returns a tuple
def concurrent_api_call_and_processing(api_call=None, callback_processing=None, lst=None, workers=5): """ :param api_call: Function that will be called concurrently. An API call to API_Provider for each entry. : param lst: List of finding's ids needed by the API function to call API_Provider endpoint. :param callback_processing: Function that will be called after we get the response from the above API call. : param workers: Number of concurrent threads that will be used. :return: array of tuples containing the details of each particular finding. """ output = Queue() with ThreadPoolExecutor(max_workers=workers) as executor: future_to_f_detail = {executor.submit(api_call, id): id for id in lst} for future in as_completed(future_to_f_detail): try: find_details = future.result() except Exception as exc: print(f"Finding {id} generated and exception: {exc}") else: f_det = callback_processing(find_details) output.put(f_det) return output I started to note some random issues, (not graceful termination) while using this method.
As I was using an array instead of a queue (output=[]), but was in doubt if I could have a race condition, I decided to refactor the code and start using a Queue (output=Queue)
My question is:
- Is my code, as it is now, free of race condition?
NOTE: I wanted to note that following Raymond Hettinger, Keynote on Concurrency, PyBay 2017, I added fuzz() sleep methods for testing but could not identify if indeed I had a race condition or not.
except Exception as exc:is bad practice, it's best to be as specific as possible.