Python 线程:只有一个线程被启动
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"
我正在尝试启动多个线程,但只有一个线程被启动,我该如何让程序继续运行并启动其他线程呢?
3 个回答
也许你从来没有等到线程结束就退出你的程序...
当程序结束时,它会直接退出,并且会终止所有线程。在退出程序之前,你必须等所有线程都结束,就像Emir Akaydın说的那样。
不要用 thread.start_new_thread(target=self.socketFunctionRead1())
这种写法,
试试 thread.start_new_thread(target=self.socketFunctionRead1)
。
因为有括号的写法会直接调用这个函数,并把它的返回值赋给 target。这样的话,thread.start_new_thread(target=self.socketFunctionRead1())
可能会导致这个函数只被调用一次,后面的线程就不会再执行了。
在 thread.start_new_thread
中,target 应该是一个可以调用的对象(也就是像函数一样可以被执行的东西)。
补充说明:
根据 Python 文档:
thread.start_new_thread(function, args[, kwargs])
启动一个新线程并返回它的标识符。这个线程会执行函数 function,并使用参数列表 args(这个参数必须是一个元组)。可选的 kwargs 参数可以指定一个关键字参数的字典。当函数执行完毕后,线程会自动退出。如果函数因为没有处理的异常而终止,会打印出错误信息,然后线程退出(但其他线程会继续运行)。
这意味着你应该用 thread.start_new_thread(self.socketFunctionRead1)
来调用。
如果你给 start_new_thread
传递关键字参数,它们会被传递给 self.socketFunctionRead1
。
线程的 target 是必须的,而不是一个关键字参数。