2017-04-26 81 views
0

我开始编写一个使用线程的程序,但在搜索如何在Python中启动线程之后,我发现了两种方法可以实现相同的功能。彼此之间必定有差异或优势。困惑我应该走下哪条路。多线程类vs方法

我的线程将持续在后台运行,并且不会停止,直到程序被用户告知为止。另外一个或多个参数将在启动时传递给线程。

一个使用方法类:

from threading import Thread 

class myClassA(Thread): 
    def __init__(self): 
     Thread.__init__(self) 
     self.daemon = True 
     self.start() 
    def run(self): 
     while True: 
      print 'A' 

myClassA() 
while True: 
    pass 

其次使用的方式方法:

from threading import Thread 

def runA(): 
    while True: 
     print 'A\n' 

if __name__ == "__main__": 
    t1 = Thread(target = runA) 
    t1.setDaemon(True) 
    t1.start() 
    while True: 
     pass 
+0

你应该在你的最后一个例子中使用't1.daemon = True'。在选择调用'__init __(。)中的.start()'之前,请确保您了解https://docs.python.org/2/library/threading.html#importing-in-threaded-code中提到的导入限制。 )全局对象的方法... – thebjorn

回答

0

我使用类的经验法则是,直到你找到一个很好的使用情况,你不应该使用它们为他们。一个用例就是如果你想定义多个方法来与线程交互。但是通常开发人员在设计类时不会看到未来,所以最好仅使用函数进行编码,并且当您看到类的用例重构代码时。我的意思是,你可能花了很多时间设计一个班级,甚至没有最终使用或需要你实施的许多功能;所以你浪费了你的时间,并且无理由地让你的代码变得复杂。