rya*_*025 1 python multithreading class function multiprocess
我想在Python中同时在类的方法中运行2个函数。我尝试使用threading模块但它不起作用。我的示例代码如下:
import os, sys
import threading
from threading import Thread
class Example():
def __init__(self):
self.method_1()
def method_1(self):
def run(self):
threading.Thread(target = function_a(self)).start()
threading.Thread(target = function_b(self)).start()
def function_a(self):
for i in range(10):
print (1)
def function_b(self):
for i in range(10):
print (2)
run(self)
Example()
Run Code Online (Sandbox Code Playgroud)
如果执行上面的代码,它只会1先打印所有 s,然后打印所有2s。然而,我想要的是同时1打印。2因此,所需的输出应该是它们混合在一起。
threading模块有能力做到这一点吗?如果不能的话,什么模块可以做到这一点?如果有人知道如何解决,请告诉我。赞赏!
你需要以不同的方式传递论点。现在,您实际上是在初始化调用中执行函数,threading.Thread而不是创建执行该函数的线程。
如果某些东西需要函数作为参数,请始终使用 just function。如果您编写function(),Python 将不会将实际函数作为参数传递,而是当场执行该函数并使用返回值。
def run(self):
threading.Thread(target = function_a, args=(self,)).start()
threading.Thread(target = function_b, args=(self,)).start()
Run Code Online (Sandbox Code Playgroud)