alv*_*vas 2 python multithreading list
据我所知,两个功能可以并行使用运行multiprocessing或threading模块,例如使在同一时间运行两个功能和Python的多重并行进程.
但以上示例仅使用打印功能.是否有可能在python中运行并行返回列表的函数,如果是,如何?
我尝试过使用线程:
from threading import Thread
def func1(x):
return [i*i for i in x]
def func2(x):
return [i*i*i for i in x]
nums = [1,2,3,4,5]
p1 = Thread(target = func1(nums)).start()
p2 = Thread(target = func2(nums)).start()
print p1
print p2
Run Code Online (Sandbox Code Playgroud)
但我得到了以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: 'list' object is not callable
None
None
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)
我已经尝试输入args参数作为元组,而不是变量:
import threading
from threading import Thread
def func1(x):
return [i*i for i in x]
def func2(x):
return [i*i*i for i in x]
nums = [1,2,3,4,5]
p1 = Thread(target = func1, args=(nums,)).start()
p2 = Thread(target = func2, args=(nums,)).start()
print p1, p2
Run Code Online (Sandbox Code Playgroud)
但它只返回None None,所需的输出应该是:
[OUT]:
[1, 4, 9, 16, 25] [1, 8, 27, 64, 125]
Run Code Online (Sandbox Code Playgroud)
线程的目标函数不能返回值.或者,我应该说,该return值被忽略,因此,不会传回产卵线程.但是这里有几件事你可以做:
1)使用返回产卵线程Queue.Queue.请注意原始函数的包装:
from threading import Thread
from Queue import Queue
def func1(x):
return [i*i for i in x]
def func2(x):
return [i*i*i for i in x]
nums = [1,2,3,4,5]
def wrapper(func, arg, queue):
queue.put(func(arg))
q1, q2 = Queue(), Queue()
Thread(target=wrapper, args=(func1, nums, q1)).start()
Thread(target=wrapper, args=(func2, nums, q2)).start()
print q1.get(), q2.get()
Run Code Online (Sandbox Code Playgroud)
2)global用于访问线程中的结果列表以及产生过程:
from threading import Thread
list1=list()
list2=list()
def func1(x):
global list1
list1 = [i*i for i in x]
def func2(x):
global list2
list2 = [i*i*i for i in x]
nums = [1,2,3,4,5]
Thread(target = func1, args=(nums,)).start()
Thread(target = func2, args=(nums,)).start()
print list1, list2
Run Code Online (Sandbox Code Playgroud)