2012-12-07 77 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如果我的答案解决了您的问题,您会考虑将其标记为已接受吗? –

相关问题