相关疑难解决方法(0)

使用协程与线程时的吞吐量差异

几天前,我提出了一个关于如何帮助我设计构建多个HTTP请求的范例的问题

这是场景.我想拥有一个多生产者,多消费者系统.我的生产者抓取并抓取一些网站,并将它找到的链接添加到队列中.由于我将抓取多个网站,我希望有多个生产者/抓取工具.

消费者/工作者以此队列为食,向这些链接发出TCP/UDP请求并将结果保存到我的Django DB.我还希望有多个工作人员,因为每个队列项目完全相互独立.

人们建议使用coroutine库,即Gevent或Eventlet.从未使用过coroutines,我读到即使编程范例类似于线程范例,只有一个线程正在执行,但是当阻塞调用发生时 - 例如I/O调用 - 堆栈在内存中切换而另一个在绿色中切换线程接管,直到它遇到某种阻塞I/O调用.希望我做对了吗?这是我的一篇SO帖子中的代码:

import gevent
from gevent.queue import *
import time
import random

q = JoinableQueue()
workers = []
producers = []


def do_work(wid, value):
    gevent.sleep(random.randint(0,2))
    print 'Task', value, 'done', wid


def worker(wid):
    while True:
        item = q.get()
        try:
            print "Got item %s" % item
            do_work(wid, item)
        finally:
            print "No more items"
            q.task_done()


def producer():
    while True:
        item = random.randint(1, 11)
        if item == 10:
            print "Signal Received"
            return
        else:
            print "Added item %s" …
Run Code Online (Sandbox Code Playgroud)

python multithreading coroutine gevent

5
推荐指数
1
解决办法
6910
查看次数

这个while循环如何退出?

那么,当线程启动时,这段代码如何退出while语句?(请不要考虑缩进)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
Run Code Online (Sandbox Code Playgroud)

**编辑*

启动线程的代码:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True) …
Run Code Online (Sandbox Code Playgroud)

python multithreading while-loop

1
推荐指数
1
解决办法
2552
查看次数

标签 统计

multithreading ×2

python ×2

coroutine ×1

gevent ×1

while-loop ×1