简体   繁体   中英

Threading, parallel 'while True' loops

I know this was asked many times, yet Im not able to get this to work. I have two separate functions, both using while True loop:

def function_1():
    while True:
        #do something

and

def function_2():
    while True:
        #do something also

I have tried running them with threading like this:

t_1 = threading.Thread(target=function_1(), args=())
t_2 = threading.Thread(target=function_2(), args=())

t_1.start()
t_2.start()

The problem is that it executes only the first one. I've also tried wrapping this into a function and call it but the results are similar. Any tips?

t_1 = threading.Thread(target=function_1)
t_2 = threading.Thread(target=function_2)

You gotta remove the brackets while passing the function to the target. In Python, functions can be treated as objects so that's why its possible

When you put brackets python essentially waits for the function_1() to return another function,which is not happening. So when you start thread 1 since function_1 is a while True func, its stuck there.

Read functions are first class objects - Dan Bader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM