Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🇷🇺🇵🇭 Russia-Philippines Political Consultations
26 November 2024
🔹 On November 26, 2024, Deputy Minister of Foreign Affairs of the Russian Federation Andrey Rudenko held political consultations with Undersecretary of Foreign Affairs of the Republic of the Philippines Maria-Theresa Lazaro in Manila.
🔹 A thorough exchange of views took place on topical issues of the bilateral, regional, and global agenda. Both sides discussed the state and perspectives of development of the Russian-Philippine political dialogue, cooperation in trade, economic and humanitarian spheres. Special attention was paid to interaction within the UN and multilateral venues of the Asia-Pacific region, including within the format of the Russia-ASEAN Dialogue.
#RussiaPhilippines
🇷🇺🇵🇭 June 2 marks 4️⃣9️⃣ years since the day our country and the Republic of the Philippines established diplomatic relations. It was on this day in 1976 that the two nations formalised their relations during the visit by President of the Philippines Ferdinand Marcos to Moscow.
🤝 For nearly half a century, the friendshipbetween our countries and peoples has stood the test of time. The experience of cooperation accumulated throughout the years has shaped the friendly nature of bilateral ties based on mutualrespect and pragmatism. The #Philippines remains one of Russia’s key partners in the #AsiaPacific region.
Dialogue is actively pursued at the governmental and interregional levels. Philippine official delegations regularly attend major international events in Russia. Notably, in September 2023, a delegation from the Philippines, led by Mayor of Cebu City Michael Lopez Rama, visited the Eastern Economic Forum in Vladivostok. Our Philippine friends have also participated in the St Petersburg International United Cultures Forum and the World Youth Festival in Sochi.
The framework of our interregional ties continues to strengthen through bilateral agreements and joint programmes. The Philippines' Cebu City has established sister-city relations with the city of Vladimir. In 2022, Cebu and Vladivostok signed a cooperation agreement. In 2024, the same deal was reached between the Cebu Province and St. Petersburg, covering trade, economy, science, technology and humanitarian issues, thus, complementing the existing partnership programmes between our respective capitals.
Our countries benefit from the efficient cooperation of legislative bodies, ministries, and governmental agencies. In November 2024 in Manila, Russia and the Philippines held consultations between the Foreign Ministries that resulted in the important agreements on the bilateral, regional and global agendas being reached.
📈 Trade and economic interaction remains an important component of bilateral relations. As of 2024, our mutual trade reached nearly $600 million. In October 2023, on the margins of the meeting of the intergovernmental Russian-Philippine Joint Commission on Trade and Economic Cooperation, a business forum was held, which brought together over 160 participants. Huge experience of constructive cooperation between our countries has been accumulated in such areas as energy, agriculture, transportation and tourism.
Cultural and humanitarian exchanges play a particularly important role in our relations. Russian ballet performances, including plays staged by renowned choreographers, always gather full halls in the leading theatres of the Philippines. In February 2024, The Philippine cybersports team Neon Esports successfully performed at the “Future Games” in Kazan. Furthermore, Russian citizens enjoy 30-day visits to the Philippines as part of the visa-free programme.
🌐 Moscow and Manila closely coordinate their actions on various international fora, including within #RussiaASEAN Dialogue. We especially value our aligned efforts at the #UnitedNations: the Philippines was among the 54 like-minded countries that co-authored Russia-sponsored resolution"Eightieth anniversary of the end of the Second World War", adopted on March 4 during the 79th Session of the UN General Assembly (#UNGA79).
🇷🇺🤝🇵🇭 On the occasion of our joint anniversary, we extend our sincere and warm congratulations to our Philippine colleagues. We appreciate the many decades of fruitfulcooperation with our partners. We are confident that the 50th anniversary of our diplomatic relations in 2026 will be marked by numerous meaningful joint initiatives!
#RussiaPhilippines