gpt4 book ai didi

Python 队列 - 线程仅绑定(bind)到一个核心

转载 作者:行者123 更新时间:2023-11-28 21:30:03 25 4
gpt4 key购买 nike

我写了一个Python脚本: 1. 提交搜索查询 2.等待结果 3.解析返回结果(XML)

我使用线程和队列模块并行执行此操作(5 个工作线程)。
它非常适合查询部分,因为我可以提交多个搜索作业并在结果出现时对其进行处理。
然而,我的所有线程似乎都绑定(bind)到同一个核心。当它到达处理 XML(CPU 密集型)的部分时,这一点很明显。

还有其他人遇到过这个问题吗?我在概念上错过了一些东西吗?

此外,我正在考虑拥有两个独立的工作队列的想法,一个用于进行查询,另一个用于解析 XML。现在,一名 worker 将连续完成这两项工作。我不确定这会给我带来什么(如果有的话)。非常感谢任何帮助。

这是代码:(专有数据已删除)

def addWork(source_list):
for item in source_list:
#print "adding: '%s'"%(item)
work_queue.put(item)

def doWork(thread_id):
while 1:
try:
gw = work_queue.get(block=False)
except Queue.Empty:
#print "thread '%d' is terminating..."%(thread_id)
sys.exit() # no more work in the queue for this thread, die quietly

##Here is where i make the call to the REST API
##Here is were i wait for the results
##Here is where i parse the XML results and dump the data into a "global" dict

#MAIN
producer_thread = Thread(target=addWork, args=(sources,))
producer_thread.start() # start the thread (ie call the target/function)
producer_thread.join() # wait for thread/target function to terminate(block)

#start the consumers
for i in range(5):
consumer_thread = Thread(target=doWork, args=(i,))
consumer_thread.start()
thread_list.append(consumer_thread)

for thread in thread_list:
thread.join()

最佳答案

这是 CPython 处理线程方式的副产品。互联网上有无穷无尽的讨论(搜索 GIL),但解决方案是使用多处理模块而不是线程Multiprocessing使用与线程几乎相同的接口(interface)(和同步结构,因此您仍然可以使用队列)构建。它只是为每个线程提供了自己的整个进程,从而避免了 GIL 和并行工作负载的强制序列化。

关于Python 队列 - 线程仅绑定(bind)到一个核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3924637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com