我也来问个 gevent 的 threadpool 问题

2016-09-22 22:08:38 +08:00
 4ever911

按我的理解, gevent 的 threadpool 应该就是通过管理 greenlet 的个数来控制当前的并发数吧。 按道理,使用 gevent 的 threadpool 不存在同步的问题呀。但是我在实际使用中,发现输出数据有点问题。

代码如下:

import gevent.monkey
gevent.monkey.patch_socket()

import gevent
import requests
from gevent.threadpool import ThreadPool
from gevent.coros import Semaphore
import datetime


def fetch(pid):
    r = requests.get('http://www.baidu.com')
    
    print 'Process', pid, ':', len(r.text)


def synchronous():
    for i in range(1,10):
        fetch(i)

def asynchronous():
    threads = []
    for i in range(1,10):
        threads.append(gevent.spawn(fetch, i))
    gevent.joinall(threads)

def asynchronousPool():
    pool = ThreadPool(10)
    for i in range(1,10):
        pool.spawn(fetch, i)      
    gevent.wait()

print('----------Synchronous----------')
synchronous()

print('----------Asynchronous----------')
asynchronous()

print('----------POOL----------')
asynchronousPool()

程序输出的 output 如下:

----------Synchronous----------
Process 1 : 2381
Process 2 : 2381
Process 3 : 2381
Process 4 : 2381
Process 5 : 2381
Process 6 : 2381
Process 7 : 2381
Process 8 : 2381
Process 9 : 2381
----------Asynchronous----------
Process 1 : 2381
Process 4 : 2381
Process 6 : 2381
Process 2 : 2381
Process 3 : 2381
Process 8 : 2381
Process 7 : 2381
Process 5 : 2381
Process 9 : 2381
----------POOL----------
ProcessProcessProcess  ProcessProcess Process25ProcessProcess  3     69 8::41  :     :: :2381:2381:  2381 
 
 23812381
238123812381
Process 7 : 2381

很奇怪的是, 用 pool 的时候,每次输出的内容都是这样无须重叠的, 按我的理解,应该和中间的异步一样,虽然顺序随机,但是输出应该是一行一行整齐的呀?

是不是我使用 gevent threadpool 打开方式不对?

2817 次点击
所在节点    Python
4 条回复
4ever911
2016-09-23 00:18:33 +08:00
我转发到 github 的开发组上面去问看看
4ever911
2016-09-23 00:50:25 +08:00
开发者真牛 x ,我发了消息,马上秒回。

jamadden commented :

A ThreadPool uses native threads, so you have exactly the same concerns that you'd have with any use of native threads.

You probably don't want to use a ThreadPool here anyway, I doubt it's going to gain you any additional concurrency over what gevent already provides.
4ever911
2016-09-23 00:52:22 +08:00
可以关闭了。。。。

可以关闭了。。。。

可以关闭了。。。。
4ever911
2016-09-23 01:21:10 +08:00
用错了,应该用 pool 而不是 thread pool

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/308276

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX