2012-12-07 75 views
3

我想知道在主線程中運行函數的可能性,其中調用函數在另一個線程中。如何運行一個線程在python外線程中調用的函數

考慮例如

from thread import start_new_thread 

def add(num1,num2): 

    res = num1 + num2 
    display(res) 

def display(ans): 
    print ans 

thrd = start_new_thread(add,(2,5)) 

我在這裏調用一個新的線程add()以下。這又稱爲display(),即,顯示器也在同一線程中運行。

我想知道如何在該線程之外運行display()

新的代碼爲每答案下面

如果我試圖接受用戶輸入並打印結果。它要求輸入只有一次,但不重複......

從螺紋進口螺紋#線程是比線程模塊 從隊列進口隊列更好

Q =隊列()#使用隊列來傳遞從消息工作線程主線程

def add(): 
    num1=int(raw_input('Enter 1st num : ')) 
    num2=int(raw_input('Enter 2nd num : ')) 
    res = num1 + num2 
    # send the function 'display', a tuple of arguments (res,) 
    # and an empty dict of keyword arguments 
    q.put((display, (res,), {})) 

def display(ans): 
    print ('Sum of both two num is : %d ' % ans) 

thrd = Thread(target=add) 
thrd.start() 

while True: # a lightweight "event loop" 
# ans = q.get() 
# display(ans) 
# q.task_done() 
    f, args, kwargs = q.get() 
    f(*args, **kwargs) 
    q.task_done() 

,當我運行的代碼,其結果是,如下

當前結果

Enter 1st num : 5 
Enter 2nd num : 6 
Sum of both two num is : 11 

所需的結果

Enter 1st num : 5 
Enter 2nd num : 6 
Sum of both two num is : 11 

Enter 1st num : 8 
Enter 2nd num : 2 
Sum of both two num is : 10 

Enter 1st num : 15 
Enter 2nd num : 3 
Sum of both two num is : 18 

,我需要它每次打印結果後,要求輸入,如下面

+0

創建一個新的線程和運行函數存在。 –

+0

@DavidHeffernan如果我創建一個新的線程和運行該功能將再次運行是另一個線程。但我不想在一個線程中運行它。它應該正常曬黑。 – Rao

+0

所有代碼都在一個線程中運行。沒有線程,什麼都不能運行。你需要更清楚。 –

回答

9

聽起來像是你想display所有調用上發生主線程。事情是這樣的單純的例子,用Queue將消息發送到主線程,應該工作:

from threading import Thread # threading is better than the thread module 
from Queue import Queue 

q = Queue() # use a queue to pass messages from the worker thread to the main thread 

def add(num1,num2): 
    res = num1 + num2 
    q.put(res) # send the answer to the main thread's queue 

def display(ans): 
    print ans 

thrd = Thread(target=add, args=(2,5)) 
thrd.start() 

while True: # a lightweight "event loop" 
    ans = q.get() 
    display(ans) 
    q.task_done() 

這個輕量級「的消息框架」的典型概括就是你的工作線程編程把任意函數並參與q。這可以讓你製作主線程笨重。那麼符合Q涉及的代碼是這樣的:

def add(num1,num2): 
    res = num1 + num2 
    # send the function 'display', a tuple of arguments (res,) 
    # and an empty dict of keyword arguments 
    q.put((display, (res,), {})) 

# snip 

while True: 
    # now the main thread doesn't care what function it's executing. 
    # previously it assumed it was sending the message to display(). 
    f, args, kwargs = q.get() 
    f(*args, **kwargs) 
    q.task_done() 

從這裏你可以看到你是如何設計一個強大的和分離的多線程應用程序。您爲每個工作線程對象裝入一個輸入Queue,全局線程負責在線程之間對消息進行混洗。

注意基於Queue的多線程方法假定沒有任何線程共享任何全局對象。如果他們這樣做,您還需要確保所有共享對象都具有關聯的鎖(請參閱the threading documentation)。當然,這很容易出現基於Queue的方法試圖避免的困難的同步錯誤。儘管看起來很辛苦,但故事的寓意是將共享狀態降到最低。

+0

我得到錯誤'f,args,kwargs = q.get() TypeError:'函數'對象不可迭代' – Rao

+0

道歉,我的代碼中存在拼寫錯誤。工作線程應該在隊列中放置一個_tuple_:'q.put((display,(res,),{}))'(注意多餘的括號)。我已經在代碼片段中修復了它。 –

+0

@PBLNarasimhaRao如果我的答案解決了您的問題,您會考慮將其標記爲已接受嗎? –

相關問題