
按我的理解, 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 打开方式不对?
1 hihihihihi OP 我转发到 github 的开发组上面去问看看 |
2 hihihihihi OP 开发者真牛 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. |
3 hihihihihi OP 可以关闭了。。。。 可以关闭了。。。。 可以关闭了。。。。 |
4 hihihihihi OP 用错了,应该用 pool 而不是 thread pool |