Параллельное Исполнение в Python с Помощью Модуля threading
В данном посте, вы узнаете, как использовать модуль threading для создания параллельных потоков выполнения и улучшения производительности ваших приложений.
threading позволяет создавать легковесные потоки, которые выполняются параллельно, ускоряя выполнение задач. Это особенно полезно в сценариях, где есть задачи, которые можно выполнить независимо друг от друга.
Пример:
import threading
import time
# Функция, которую будем выполнять в параллельных потоках
def print_numbers():
for i in range(5):
time.sleep(1) # Эмулируем длительную операцию
print(f"Thread {threading.current_thread().name}: {i}")
# Создаем два потока
thread1 = threading.Thread(target=print_numbers, name="Thread 1")
thread2 = threading.Thread(target=print_numbers, name="Thread 2")
# Запускаем потоки
thread1.start()
thread2.start()
# Ожидаем завершения потоков перед завершением программы
thread1.join()
thread2.join()
print("Главный поток выполнения завершен.")
В данном примере создаются два потока, каждый из которых выполняет функцию print_numbers, эмулируя длительную операцию с использованием time.sleep. Запуск потоков осуществляется с помощью метода start(), и главный поток ожидает их завершения с использованием метода join().
Модуль threading предоставляет удобные средства для работы с параллельными потоками в Python, что позволяет улучшить производительность приложений. Однако, следует быть внимательными при работе с потоками из-за потенциальных проблем с блокировками и синхронизацией данных. Попробуйте интегрировать threading в свой код и ускорьте выполнение задач!
💻
#python#threading
#Python
🐍
Como todos conocen #Python es un lenguaje de alto nivel de programación e interpretado cuya filosofía hace hincapié en la legibilidad de su código y se utiliza para desarrollar aplicaciones de todo tipo.
A sugerencia de ustedes hemos creado un grupo donde recopilaremos todo el material disponible agrupado por temas, al que pueden unirse aquí:
👇
🔗Link
-----
Canal principal: @repo_science
Cupones: @freecoupons_reposcience
-----
Version 3.10 of the legendary programming language is now here: https://www.python.org/downloads/release/python-3100
No rush to update, though. #Python
#python
Our internet is broken again, and this time by Python setuptools.
[BUG] Version 78.0.1 breaks install of ansible-vault package · Issue #4910 · pypa/setuptools
https://github.com/pypa/setuptools/issues/4910
#Python is the main language of data science, per this analysis on 10M Jupyter Notebooks: https://blog.jetbrains.com/datalore/2020/12/17/we-downloaded-10-000-000-jupyter-notebooks-from-github-this-is-what-we-learned/
#python
I had the wrong idea for a long time that IDEs treat method/function without return type hint as returning None type.
I was wrong. In PEP484, it says IDE should treat such a method/function as a type that is as general as possible. Ah that just makes sense.
https://peps.python.org/pep-0484/#the-meaning-of-annotations
#python
This post is a retro on how I learned Python.
Disclaimer: I can not claim that I am a master of Python. This post is a retrospective of how I learned Python in different stages.
I started using Python back in 2012. Before this, I was mostly a Matlab/C user.
Python is easy to get started, yet it is hard to master. People coming from other languages can easily make it work but will write some "disgusting" python code. And this is because Python people talk about "pythonic" all the time. Instead of being an actual style guide, it is rather a philosophy of styles.
When we get started, we are most likely not interested in [PEP8](https://peps.python.org/pep-0008/) and [PEP257](https://peps.python.org/pep-0257/). Instead, we focus on making things work. After some lectures from the university (or whatever sources), we started to get some sense of styles. Following these lectures, people will probably write code and use Python in some projects. Then we began to realize that Python is strange, sometimes even doesn't make sense. Then we started leaning about the philosophy behind it. At some point, we will get some peer reviews and probably fight against each other on some philosophies we accumulated throughout the years.
The attached drawing (in comments) somehow captures this path that I went through. It is not a monotonic path of any sort. This path is most likely to be permutation invariant and cyclic. But the bottom line is that mastering Python requires a lot of struggle, fights, and relearning. And one of the most effective methods is peer review, just as in any other learning task in our life.
Peer review makes us think, and it is very important to find some good reviewers. Don't just stay in a silo and admire our own code. To me, the whole journey helped me building one of the most important philosophies of my life: embrace open source and collaborate.