Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
from fastapi.concurrency import run_in_threadpool
async def execute(data: DataRequest) -> DataResponse:
try:
result = await run_in_threadpool(sync_function, data)
return DataResponse(data=result)
except Exception as e:
return DataResponse(
error=str(e),
success=False,
)
В общем работает нормально. Для всех вызовов под капотом используется общий тредпул, всё работает предсказуемо.
Но потребовалось изменить количество запускаемых в пуле потоков (по умолчанию создается 40 воркеров).
Так как дело происходит с FastAPI, делается это через lifespan используя настройки anyio:
import anyio
@asynccontextmanager
async def lifespan(app: FastAPI):
limiter = anyio.to_thread.current_default_thread_limiter()
limiter.total_tokens = 100
yield
# если вдруг нужно вернуть обратно
limiter.total_tokens = 40
Зачем менять количество воркеров?
- уменьшить, если оперативки мало (один тред занимает ~8мб)
- увеличить чтобы выдержать нагрузку
Если есть предложения получше при тех же вводных - предлагайте😉
#async
🚀 Iran's Ten-Point Plan Gains Consensus as Negotiation Framework
On April 10, Iran's Deputy Foreign Minister Ravanchi announced during a meeting with foreign diplomats and international organization representatives in Iran that a consensus has been reached to use Iran's ten-point plan as the basis for negotiations. According to BlockBeats, Ravanchi emphasized Iran's openness to diplomacy and dialogue but firmly rejected any discussions based on false information intended to deceive or pave the way for renewed military aggression against Iran.
#Iran#Diplomacy#Negotiation#InternationalRelations#ForeignPolicy
🚀 Dollar Faces Pressure Amid US-Iran Negotiation Reports
The dollar-and-oil buying trade is experiencing challenges as reports of negotiations between the United States and Iran surface. According to NS3.AI, the US Dollar Spot Index has decreased by approximately 1.4% this week, marking its largest weekly drop since January. This decline is attributed to shifts in foreign exchange trading, influenced by headlines surrounding the negotiations and a fragile ceasefire.
#Dollar#US#Iran#Negotiation#Forex#Oil#Ceasefire#CurrencyMarket
🚀 Trump Denounces Reports on Iran Negotiation Plan as False
U.S. President Donald Trump has criticized reports from The New York Times and CNN regarding a ten-point plan on Iran negotiations. According to Odaily, Trump labeled these reports as entirely fabricated and aimed at discrediting those involved in the peace process. He dismissed the points as fraudulent schemes and called the media outlets 'evil losers.' Trump concluded his statement with a call to 'Make America Great Again.'
#Trump#Iran#Negotiation#USPolitics#Media#FakeNews#PeaceProcess#MAGA
🚀 Trump Criticizes Iran's Media Tactics on Truth Social
U.S. President Donald Trump expressed his views on Iran's media strategies on April 11 via Truth Social. According to BlockBeats, Trump stated that Iranians are more adept at handling fake news media and public relations than engaging in warfare. He remarked that Iran seems unaware of its lack of leverage, aside from short-term 'extortion' through international waterways. Trump concluded that Iran's current existence is solely for negotiation purposes.
#Trump#Iran#MediaTactics#FakeNews#PublicRelations#Negotiation#TruthSocial#Extortion#InternationalWaterways