Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🔴📺Netanyahu doit relâcher immédiatement les douze membres de l’équipage de la #FreedomFlotilla !
👉https://youtu.be/ESd_d14gNQ4
Bon visionnage et n'hésitez pas à partager !
-----------
On vous a transféré ce message ? Abonnez-vous au canal Telegram de Jean-Luc Mélenchon sur : https://t.me/JLMelenchon
Se tenir prêt. Communiquer. Rima, Greta et le petit bateau anti blocus s'approche de la côte. Les commandos meurtriers de Netanyahu sont prêts à bondir.
#FreedomFlotilla
👉Partager sur Twitter
👉Partager sur Bluesky
-----------
On vous a transféré ce message ? Abonnez-vous au canal Telegram de Jean-Luc Mélenchon sur : https://t.me/JLMelenchon
🔴En direct avec Rima Hassan - Ne quittons pas des yeux Freedom Flotilla !
J'ai échangé avec Rima Hassan sur Al-Jazeera à bord du #FreedomFlotilla pour lui dire toute mon admiration pour son courage et sa détermination.
N'hésitez pas à partager et à continuer de les soutenir !
👉https://youtu.be/DBU_VjUAi4M
-----------
On vous a transféré ce message ? Abonnez-vous au canal Telegram de Jean-Luc Mélenchon sur : https://t.me/JLMelenchon
Le forze armate israeliane intervengono sulla flotta #FreedomFlotilla, a bordo ci sono 3 parlamentari nazionali del Parlamento della Repubblica di #Turchia.
🔴URGENT - Rassemblement pour libérer la Flottille de la Liberté et contre le génocide à Gaza !
Ce lundi 9 juin à 18h, rendez-vous à la Place de la République à Paris.
Soyons nombreuses et nombreux ! Merci de partager ce message !
#FlottilleDeLaLiberté#FreedomFlotilla
-----
Plus d'infos : https://t.me/FranceInsoumise
🔴URGENT - Rassemblement pourla libération sans conditions des prisonniers et la fin du blocus à Gaza !
Ce mardi 10 juin à 18h, rendez-vous à la Place de la République à Paris.
Soyons nombreuses et nombreux ! Merci de partager ce message !
#FlottilleDeLaLiberté#FreedomFlotilla#StopGenocide
-------
Plus d'infos : https://t.me/FranceInsoumise
Tareq, from Gaza, was one of the dozens of international volunteers, ready to sail to Palestine with aid and revolutionary hope. This is why he joined the Freedom Flotilla Coalition, and why we must continue fighting for the 'Conscience', which is currently still stranded in international waters. #AllEyesOnDeck#FreedomFlotilla#StandWithGaza. ⬇️
Dopo giorni di navigazione nel Mediterraneo orientale, la Handala – la nave umanitaria della Freedom Flotilla Coalition – è stata ufficialmente intercettata dalle forze navali israeliane mentre si avvicinava alla Striscia di Gaza. Il blocco è avvenuto mentre la nave si trovava a circa 100 miglia marine dalla costa, in acque internazionali, e sotto costante sorveglianza aerea da parte di un drone israeliano Heron.
Il viaggio della Handala era cominciato il 13 luglio 2025, quando ha lasciato il porto di Siracusa con a bordo 19 attivisti internazionali, tra cui due italiani.
La nave ha puntato la prua verso Gaza, portando con sé alcuni aiuti simbolici: medicinali essenziali, latte in polvere, alimenti base e giocattoli per i bambini della Striscia. Una missione dalla forte valenza politica e umanitaria: rompere simbolicamente il blocco navale israeliano e denunciare la situazione drammatica che vive la popolazione palestinese.
#gazagenocide#handala#freedomflotilla#israel#idf
UN EXPERTS DEMAND SAFE PASSAGE FOR ‘MADLEEN’
JOIN THEM
Today, UN experts called for safe passage for the Madleen — our civilian ship carrying vital aid and international volunteers to Gaza.
Now we need your voice. Let’s turn international law into action.
📣 Take one minute: go to bit.ly/IsraelOnNotice and send a letter to the Israeli government, UN officials, and diplomatic missions demanding that Israel abide by international law and refrain from attacking, sabotaging or otherwise interfering with the Madleen and her mission.
Together, we can open a people’s sea corridor to Gaza. #SafePassage#BreakTheSiege#FreedomFlotilla
Hours before the Freedom Flotilla’s ship, the ‘Conscience’, was about to be boarded by dozens of volunteers from over 21 countries (including high profile activists), the ship was attacked by two drones. Signal was cut and information about the number of people on board was not clear. SOS distress signals were ignored. Here is what happened. #AllEyesOnDeck#DemandSafePassage#FreedomFlotilla
"‘We Need More Angry Young Women’ To End Israeli #Genocide Of #Gaza... And Fewer Angry, Old, White Politicians."
Climate Activist and Gaza #FreedomFlotilla volunteer Greta Thunberg’s response to Trump’s assertion that she needs anger management.
By Ann Wright, in Popular Resistance.
https://popularresistance.org/we-need-more-angry-young-women-to-end-israeli-genocide-of-gaza/
The Freedom Flotilla Coalition is setting sail again.
Join us in Siracusa, Italy — or online — on July 13 at 10:30 CEST (GMT+2) as we launch ‘Handala’ on its journey toward Gaza.
Just weeks after Israeli forces illegally seized our boat ‘Madleen’ and abducted 12 unarmed civilians in international waters, we continue — with global solidarity — to challenge Israel’s illegal and deadly siege.
This mission is for the children of Gaza.
#FreedomFlotilla#WeWillSail#AllEyesOnDeck#BreakTheSiege#Handala