Answer the question
In order to leave comments, you need to log in
How to run two Python threads at the same time?
from threading import Thread
from time import sleep
from threading import Thread
from time import sleep
def func():
print("h", end = "") #ДОЧЕРНИЙ ПОТОК
print("e", end = "") #ДОЧЕРНИЙ ПОТОК
print("l", end = "") #ДОЧЕРНИЙ ПОТОК
print("l", end = "") #ДОЧЕРНИЙ ПОТОК
print("o", end = "") #ДОЧЕРНИЙ ПОТОК
th1 = Thread(target=func)
th1.start()
print("h", end = "") #ВЫПОЛНЯЕТСЯ В main thread
print("e", end = "") #ВЫПОЛНЯЕТСЯ В main thread
print("l", end = "") #ВЫПОЛНЯЕТСЯ В main thread
print("l", end = "") #ВЫПОЛНЯЕТСЯ В main thread
print("o", end="") #ВЫПОЛНЯЕТСЯ В main thread
#ВЫВОД: hheelllolo
-----------------------------------------------------------------------
#А КОГДА ЗАПУСКАЮ 2 ПОТОКА ВЫВОДИТ:
from threading import Thread
from time import sleep
from threading import Thread
from time import sleep
def func():
print("h", end = "") #ДОЧЕРНИЙ ПОТОК
print("e", end = "") #ДОЧЕРНИЙ ПОТОК
print("l", end = "") #ДОЧЕРНИЙ ПОТОК
print("l", end = "") #ДОЧЕРНИЙ ПОТОК
print("o", end = "") #ДОЧЕРНИЙ ПОТОК
th1 = Thread(target=func)
th2 = Threa(target=func)
th1.start()
th2.start()
#ВЫВОД: hello
# hello
#**КАК ЗАПУСТИТЬ ОДНОВРЕМЕННО ДВА ПОТОКА?**
Answer the question
In order to leave comments, you need to log in
Most likely, the func function is executed so quickly that it does not reach the thread switching and does not reach
ZY stripped print with "long" operations
There is a problem in CPython - one thread is always executed at a time, even if the processor has several cores. So it's problematic to run two threads "simultaneously" in python. They will alternate, performed piece by piece. The exception is if the thread is waiting for an I/O operation to complete, or something similar, i.e. does not directly execute python code. Then it doesn't block other threads.
However, there are no guarantees about the order of their execution. When the OS decides to switch from one thread to another, you have no control. For example, your first code also outputs "hellohello" to me.
So yes, your code is running as "simultaneously" as possible.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question