81 views
Какие недостатки и ограничения есть у выполнения блокирующей функции в отдельном потоке?
Asked at
AI answer
Moving a blocking call to a separate thread helps keep the main thread or event loop from being blocked, but has limitations:
- GIL in CPython: Threads generally do not speed up CPU-bound Python code. They are more useful for I/O operations; for computations, processes or native code that releases the GIL are often a better fit.
- A thread cannot be safely stopped forcibly. Canceling a task that is awaiting a thread usually does not stop a blocking function that is already running. Timeouts and a cooperative stop mechanism are needed.
- Limited pool capacity: If all worker threads are busy with long-running calls, new tasks have to wait. Submitting tasks without limits can cause the queue to grow and increase latency.
- Synchronization and race conditions: Shared state must be accessed carefully; locks can lead to deadlocks.
- Overhead and complexity: Creating threads, context switching, handling exceptions, and transferring data all come at a cost.
For blocking I/O calls, a bounded thread pool, timeouts, and limits on the number of concurrently running tasks are commonly used.
Also asked at GigaChat / Сбер
- app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() def heavy_text_parser(file_id: int, db: Session): # Parsing a file that takes 5 minutes parse_and_save(file_id, db) @app.post("/upload") async def upload_file( background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): file_id = save_file_to_db(db) db.commit() background_tasks.add_task(heavy_text_parser, file_id, db) return {"status": "parsing started"}
- def extract_emails_from_huge_file(file_path: str) -> list[str]: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Заменяем переносы строк, чтобы текст был "сплошным" content = content.replace('\r\n', ' ').replace('\n', ' ') lines = content.split(' ') emails = [word for word in lines if '@' in word] return emails
Similar questions
- What is the difference between an asynchronous approach and a multithreaded approach?
- Why use asynchronous programming if the tasks are the same?
- How does asynchrony work? When should it be used, and what causes switching between tasks?
- Multithreading and concurrency—what is the difference between these two concepts?
- Приходилось ли писать многопоточный код на Python без asyncio (threading, multiprocessing)?