2017-10-19 177 views
1

我想在Python中同时在一个类的方法内运行2个函数。我试图使用threading模块,但它不起作用。我的例子代码如下:在类Python的一个方法内部执行两个函数

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() 

如果上面的代码得到执行,它将只打印所有1第一个,然后将所有2秒。但是,我想要的是同时打印12。因此,期望的输出应该是混合起来的。

threading模块能够做到这一点吗?如果不是,哪个模块可以做到这一点?如果有人知道如何解决它,请让我知道。感谢!

回答

1

您需要以不同的方式传递参数。现在,您实际上正在执行初始化调用threading.Thread中的函数,而不是创建执行该函数的线程。

如果需要某个功能作为参数,请始终使用function。如果您编写function(),则Python不会将实际函数作为参数传递,而是在当场执行该函数并使用返回值。

def run(self): 
    threading.Thread(target = function_a, args=(self,)).start() 
    threading.Thread(target = function_b, args=(self,)).start() 
0

这就是:

import os, sys 
import threading 
from threading import Thread 
import time 

class Example(): 
    def __init__(self): 
     self.method_1() 

    def method_1(self): 

     def run(self): 
      threading.Thread(target = function_a, args = (self,)).start() 
      threading.Thread(target = function_b, args = (self,)).start() 

     def function_a(self): 
      for i in range(10): 
       print (1) 
       time.sleep(0.01) # Add some delay here 

     def function_b(self): 
      for i in range(10): 
       print (2) 
       time.sleep(0.01) # and here 


     run(self) 


Example() 

你会得到输出是这样的:

1 
2 
1 
2 
2 
1 
2 
1 
2 
1 
2 
1 
2 
1 
2 
1 
2 
1 
2 
1 
+0

我不认为这回答了这个问题,因为这个问题是关于一个类中做的一切而不是将组件写出来或创建新的类。 – Hannu

+0

看起来你有一个点,我会尽量正确地修改它。 –

相关问题