0

I try to launch this code on my computer and threading doesn't work:

import threading


def infinite_loop():
    while 1 == 1:
        pass

def myname():
    print("chralabya")


t1 = threading.Thread(target=infinite_loop())
t2 = threading.Thread(target=myname())

t1.start()
t2.start()

When I execute this program myname() is never executed. Can someone can explain to me why threading doesn't work?

Timus
  • 10,974
  • 5
  • 14
  • 28
xelov35
  • 9
  • 2
  • When i execute this program myname() is never execute – xelov35 Nov 18 '22 at 11:52
  • Not the original mistake, but related issue: https://stackoverflow.com/questions/1294382/what-is-the-global-interpreter-lock-gil-in-cpython – moooeeeep Nov 18 '22 at 11:59
  • `myname` is not executed because you are calling `infinite_loop` yourself which never returns. So execution never reaches the line `t2 = threading.Thread(target=myname())` – Anwar Husain Nov 18 '22 at 12:10

1 Answers1

1

target=inifinite_loop() calls your function (note the ()) and assigns the result (which never comes) to the target parameter. That's not what you want!

Instead, you want to pass the function itself to the Thread constructor:

t1 = threading.Thread(target=infinite_loop)
t2 = threading.Thread(target=myname)
Thomas
  • 174,939
  • 50
  • 355
  • 478