Reputation: 3
I can't seem to bring multithreading to work. I simplified my problem and I still can't get my threads to print properly (so I guess they're not executing correctly).
import time, threading
s_print_lock = threading.Lock()
def s_print(*a, **b):
with s_print_lock:
print(*a, **b)
# Thread safe print function
def a():
while True:
s_print('\'a\' is running')
time.sleep(5)
# Thread 1
def b():
while True:
s_print('\'b\' is running')
time.sleep(5)
# Thread 2
if __name__ == "__main__":
t1 = threading.Thread(target=a())
t2 = threading.Thread(target=b())
t1.start()
t2.start()
And the output is:
'a' is running
'a' is running
'a' is running
'a' is running
...
Upvotes: 0
Views: 193
Reputation: 130
The target must be a callable. You are executing a()
so it's getting in the while True
loop and never ending, so never starting the thread. Try this:
if __name__ == "__main__":
t1 = threading.Thread(target=a)
t2 = threading.Thread(target=b)
t1.start()
t2.start()
Upvotes: 1