Reputation: 41
I'm working with Python's asyncio and triing to understand the run_in_executor function with the default ThreadPoolExecutor to handle blocking tasks asynchronously. My concern is regarding accessing shared variables within these tasks.
My understanding is: When I use run_in_executor with a ThreadPoolExecutor, the tasks are executed in separate threads. Therefore, to ensure thread safety and prevent race conditions, I should use synchronization primitives like locks when accessing shared variables, just as I would with the threading module.
Is my understanding correct, or does asyncio handle shared variables differently in this context?
Upvotes: 0
Views: 69
Reputation: 251
Yes, your understanding is correct. A thread with asyncio event loop is a normal thread that races equally with other threads. Also, threads started via run_in_executor()
have no special semantics, and this method just comes as a wrapper so that you can asynchronously get a result (or exception) after the thread executes. But there are some points to consider:
However, note that in a free-threaded mode, threads can be executed in true parallel. This is why you should not use primitives from the threading module unless you are sure that the lock will be held for a very short time: you can thus limit the concurrency of asynchronous tasks.
Upvotes: 0