2017-10-19 56 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

看起來你有一個點,我會盡量正確地修改它。 –

相關問題