简体   繁体   中英

Python Threads: only one thread gets launched

thread.start_new_thread(target=self.socketFunctionRead1())
print "Thread 1"
thread.start_new_thread(target=self.socketFunctionWrite1())
print "Thread 2"
thread.start_new_thread(target=self.socketFunctionRead2())
print "Thread 3"
thread.start_new_thread(target=self.socketFunctionWrite2())
print "Thread 4"

I am trying to start multiple threads, but only one thread is started, how can I make the program go further by starting the other threads?

Instead of thread.start_new_thread(target=self.socketFunctionRead1()) ,

try thread.start_new_thread(target=self.socketFunctionRead1)

Because of the parenthese, the function is called and the return value of the function is assigned to target. Since thread.start_new_thread(target=self.socketFunctionRead1()) is probably a blocking call, only this function gets called.

In thread.start_new_thread, target should be a callable (An object that behaves like a function).

Edit:

From the Python documentation :

thread.start_new_thread(function, args[, kwargs])

Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

This means that you should call thread.start_new_thread(self.socketFunctionRead1).

If you pass keyword arguments to start_new_thread, they will get passed to self.socketFunctionRead1.

The target for your thread is required and not a keyword argument.

Maybe you just never wait the end of the thread before quit your program...

When the program end, it quit, and kill all thread. You must wait the end of all thread before quit your program, like Emir Akaydın said

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