Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Bob Suberi, a U.S. and Israeli citizen and veteran, calls himself a “recovering Zionist.” Now in his third year attempting to help break Israel's illegal siege of Gaza on 'Handala', he’s taking direct action once again. After years working in Palestinian solidarity in the West Bank, Suberi is urging others, especially in the Jewish community, to speak out: “Let’s talk openly about a genocide. We’ve spent decades saying ‘Never again,’ and yet we’re justifying it.”
#BreakTheSiege#BreakIsraelsSiege#EndTheBlockade#Handala#FreedomFlotilla#StandWithGaza#StandWithPalestine
Thousands of people are rising across continents - on foot, in boats, in streets and squares - to say no more.
No more siege. No more starvation. No more occupation. No more genocide. From the river to the sea, Palestine will be free. Follow and support March to Gaza today.
#BreakTheSiege#MarchToGaza#EndTheBlockade#GlobalMarchToGaza#StandWithPalestine
Nicole Jenes came to Malta to stand with the Freedom Flotilla's humanitarian action, not as an act of "rebellion", but as a reflection of what it means to be human. “This is the natural reaction to genocide, to Apartheid, to silence.” Despite drone attacks targeting the ship, no one is deterred. The volunteers and our supporters are undaunted, and together, we will push forward to Gaza. The power to break injustice lies within us. No more waiting. No more excuses.
SIGN THE PETITION - https://bit.ly/alleyesondeck
#AllEyesOnDeck#FreedomFlotilla#NicoleJenes#StandWithGaza#StandWithPalestine#BreakIsraelsSiege#EndTheBlockade
Now with Israel's attack on Iran, the airports are shut down, and our three remaining 'Madleen' team members, Pascal Maurieras, Yanis Mhamdi, and Marco van Rennes may face an extra month, illegally detained in Israeli prison.
All three were meant to be released and flying back to their families today, June 13. The French and Dutch governments must find alternative routes and get their citizens home, whether through Jordan or otherwise - NOW.
Contact details in our slides and email template in our stories.
#BreakIsraelsSiege#EndTheBlockade#Madleen#WeWillSail#AllEyesOnDeck#StandWithMadleen#StandWithPalestine
Freedom Flotilla Official Update: It's time for our governments to do their jobs and sanction Israel. Its illegal attack on 'Madleen' while sailing in international waters is a small extension of their war crimes in Gaza. Governments, institutions, media, and corporations must stop protecting Israel, now. They must stop prioritising profit over human lives, now. Protect our volunteers while protecting Palestinians in Gaza and wider Palestine.
#BreakIsraelsSiege#EndTheBlockade#Madleen#FreedomFlotilla#Volunteers#IOF#StandWithGaza#StandWithPalestine
Israel’s attack on an unarmed humanitarian vessel in European waters, and the government silence that followed, is part of a wider pattern: 19 months of Israel's relentless violence in Gaza and 77 years of impunity across occupied Palestine.
While Malta’s newly released report confirms what we already knew, there has still been no condemnation issued. No investigation. No accountability.
As we prepare to sail again with ‘Madleen’, we do so knowing our ships remain targets, not only of Israeli aggression but of global inaction.
We call on governments to guarantee safe passage, on media to report the truth, and on people everywhere to demand an end to Israel’s siege and ongoing genocide:
– Share this post and tag the EU Commission and your MEPs
– Sign our petition to demand an independent investigation
– Demonstrate at weapons manufacturers
– Keep #AllEyesOnDeck as ‘Madleen’ sails
#BreakTheSiege#EndTheBlockade#StandWithGaza#StandWithPalestine#EU#Malta#Conscience
Freedom Flotilla Official Update: It's time for our governments to do their jobs and sanction Israel. Its illegal attack on 'Madleen' while sailing in international waters is a small extension of their war crimes in Gaza. Governments, institutions, media, and corporations must stop protecting Israel, now. They must stop prioritising profit over human lives, now. Protect our volunteers while protecting Palestinians in Gaza and wider Palestine.
#BreakIsraelsSiege#EndTheBlockade#Madleen#FreedomFlotilla#Volunteers#IOF#StandWithGaza#StandWithPalestine
"The governments of the world failed to provide safe passage to the Madleen, to allow humanitarian aid to the people of Gaza, who have been facing ethnic cleansing for 80 years and an illegal blockade for 18 years. To prevent ongoing Israeli war crimes they must immediately step up, oppose the apartheid regime of Israel and provide safe passage to the Sumoud convoy in Egypt. The time to act is now. Free Palestine!"
Mark Van Rennes
#FreePalestine#SumoudConvoy#MarchToGaza#Madleen#StandWithGaza#StandWithPalestine#FreeMadleen#WeWillSail#BreakTheSiege#BreakIsraelsSiege#EndTheBlockade