推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
aoscici2000
V2EX  ›  Python

关于使用协程的一点疑问

  •  
  •   aoscici2000 · Dec 23, 2019 · 4632 views
    This topic created in 2332 days ago, the information mentioned may be changed or developed.
    class ProductDetailHandler(BaseHandler):
    
        async def get(self):
            _id     = self.get_argument('id')
            product = await mgo.product.find_one({'_id': ObjectId(_id)})
            sku     = await mgo.sku.find({'pid': _id}).to_list(None)
            seller  = await mgo.user.find_one({'_id': product['seller_id']})
            product['seller'] = seller['name']
            product['sku']    = sku
            self.write({'err_code': 0, 'data': product})
    

    像网上找的这个例子, 有一点小疑问, 这里本身 get() 就是一个协程函数了吧? 里面再开三个的话, 它自身不就是等于没事做了吗? 这算不算一种资源浪费?

    6 replies    2019-12-23 22:44:02 +08:00
    wzwwzw
        2
    wzwwzw  
       Dec 23, 2019
    await 会把 cpu 资源让出来。
    keepeye
        3
    keepeye  
       Dec 23, 2019
    asyncio.ensure_future 可以不用 await
    CzaOrz
        4
    CzaOrz  
       Dec 23, 2019   ❤️ 1
    好像是 tornado~,你说的再开三个是指三次`await`,但是后面我没懂。
    三次`await`就是三次`中断`,每次中断都有注册`任务`添加到`期程`的操作。注册后会释放 CPU 资源,之后就是等待或者执行其他已完成的`任务`,所以并没有浪费资源,整个流程没有线程的切换,效率高。而任务什么时候完成,由操作系统调度通知。
    aoscici2000
        5
    aoscici2000  
    OP
       Dec 23, 2019
    @CzaOrz 大概懂了, 谢谢哈
    676529483
        6
    676529483  
       Dec 23, 2019
    单次调用肯定没区别啊,执行次数越多,优势越大
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5876 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 06:11 · PVG 14:11 · LAX 23:11 · JFK 02:11
    ♥ Do have faith in what you're doing.