我想知道在主线程中运行函数的可能性,其中调用函数在另一个线程中。如何运行一个线程在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
,我需要它每次打印结果后,要求输入,如下面
创建一个新的线程和运行函数存在。 –
@DavidHeffernan如果我创建一个新的线程和运行该功能将再次运行是另一个线程。但我不想在一个线程中运行它。它应该正常晒黑。 – Rao
所有代码都在一个线程中运行。没有线程,什么都不能运行。你需要更清楚。 –