J
J
Jotyu2022-01-19 21:55:01
Python
Jotyu, 2022-01-19 21:55:01

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

3 answer(s)
D
Dr. Bacon, 2022-01-19
@Jotyu

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

V
Vindicar, 2022-01-19
@Vindicar

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.

L
link_vrb, 2022-01-19
@link_vrb

1) You import both libraries twice
2) in the line th2=... you have Threa instead of Thread
3) I have the hellohello output after correcting your code, and if you don’t have such an output, then the problem is not in the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question