Python队列线程仅绑定到

2024-04-25 04:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个python脚本: 1提交搜索查询 2等待结果 三。分析返回的结果(XML)

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

还有人遇到过这个问题吗?我是否在概念上遗漏了什么?在

另外,我还在考虑有两个独立的工作队列,一个用于查询,另一个用于解析XML。现在是这样,一个工人可以串行地完成这两个任务。我不知道那会给我带来什么。非常感谢任何帮助。在

代码如下:(删除了专有数据)

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()

Tags: producertheintargetforherequeueconsumer
2条回答

使用CPython,您的线程将永远不会在两个不同的内核中并行运行。查找有关全局解释器锁(GIL)的信息。在

基本上,互斥锁保护解释器的实际执行部分,因此没有两个线程可以并行计算。由于阻塞,I/O任务的线程处理将很好地工作。在

编辑:如果要充分利用多个核心,则需要使用多个进程。有很多关于这个话题的文章,我想给你找一篇我记得很棒的文章,但是找不到。在

正如Nathan建议的那样,您可以使用多处理模块。有一些工具可以帮助您在进程之间共享对象(看看POSH,Python对象共享)。在

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

相关问题 更多 >