Python 使用队列时区分返回值和线程
这是我的代码:Python 使用队列时区分返回值和线程,python,multithreading,queue,Python,Multithreading,Queue,这是我的代码: queue=Queue.Queue() isbn=str(9789382711056) thread1= Thread(target = amazon, args=[isbn,queue]) thread2= Thread(target = bookadda, args=[isbn,queue]) thread3= Thread(target = infibeam, args=[isbn,queue]) def jo():
queue=Queue.Queue()
isbn=str(9789382711056)
thread1= Thread(target = amazon, args=[isbn,queue])
thread2= Thread(target = bookadda, args=[isbn,queue])
thread3= Thread(target = infibeam, args=[isbn,queue])
def jo():
thread1.join()
thread2.join()
thread3.join()
thread1.start()
thread2.start()
thread3.start()
jo()
每个函数都在队列中放入一个列表(queue.put(list))。
其中一个函数的代码:
def infibeam(isbn,queue):
#b_price and b_avail are obtained from some where else
blist =[b_price,b_avail]
queue.put(blist)
其他方法也与此类似
我得到了队列中的所有列表,但是我怎么知道哪个方法返回了哪个列表呢?
请帮帮我。这可能是一个非常愚蠢的问题,但我对python还是新手。提前感谢。让每个线程用唯一的标记(字符串、线程函数本身等)标记其返回值。然后让主线程检查标记,找出哪个函数生成了哪个列表
作为上述方法的一种变体,让线程函数将其返回值放入字典(同样,由某种类型的唯一标记键入)。让每个线程用唯一标记(字符串、线程函数本身等)标记其返回值。然后让主线程检查标记,找出哪个函数生成了哪个列表 作为上述方法的一种变体,让线程函数将其返回值放入字典(同样,由某种类型的唯一标记键入)。如果使用,则可以使用
池。map
:
import multiprocessing.pool as mpool
def worker(target, isbn):
return target(isbn)
def amazon(isbn):
...
def bookadda(isbn):
...
def infibeam(isbn):
#b_price and b_avail are obtained from some where else
return [b_price, b_avail]
pool = mpool.ThreadPool()
isbn = str(9789382711056)
args = [(target, isbn) for target in (amazon,bookadda,infibeam)]
result = pool.map(worker, args)
multiprocessing.ThreadPool
的API与相同,只是池由线程而不是进程组成
result
中的项目顺序对应于args
中的项目顺序
在Python3中,您可以使用: 文档中还显示了如何将参数与结果相关联。如果使用,则可以使用
pool.map
:
import multiprocessing.pool as mpool
def worker(target, isbn):
return target(isbn)
def amazon(isbn):
...
def bookadda(isbn):
...
def infibeam(isbn):
#b_price and b_avail are obtained from some where else
return [b_price, b_avail]
pool = mpool.ThreadPool()
isbn = str(9789382711056)
args = [(target, isbn) for target in (amazon,bookadda,infibeam)]
result = pool.map(worker, args)
multiprocessing.ThreadPool
的API与相同,只是池由线程而不是进程组成
result
中的项目顺序对应于args
中的项目顺序
在Python3中,您可以使用:
文档中还显示了如何将参数与结果关联。这是可以做到的,但我有大约20个这样的函数,很难搜索每个列表以检查列表所属的位置。除了使用队列,还有其他选择吗?@gingernija23:将所有这些功能封装在一个类中,并在20个位置使用它。这是可以做到的,但我有大约20个这样的函数,很难搜索每个列表以检查列表所属的位置。除了使用队列,还有其他选择吗?@gingernija23:将所有这些功能封装在一个类中,并在20个位置使用它。