V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-12-23 17:11:38 +08:00 · 3631 次点击
    这是一个创建于 1579 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2019-12-23 22:44:02 +08:00
    wzwwzw
        2
    wzwwzw  
       2019-12-23 18:43:02 +08:00
    await 会把 cpu 资源让出来。
    keepeye
        3
    keepeye  
       2019-12-23 19:01:43 +08:00
    asyncio.ensure_future 可以不用 await
    CzaOrz
        4
    CzaOrz  
       2019-12-23 20:34:10 +08:00   ❤️ 1
    好像是 tornado~,你说的再开三个是指三次`await`,但是后面我没懂。
    三次`await`就是三次`中断`,每次中断都有注册`任务`添加到`期程`的操作。注册后会释放 CPU 资源,之后就是等待或者执行其他已完成的`任务`,所以并没有浪费资源,整个流程没有线程的切换,效率高。而任务什么时候完成,由操作系统调度通知。
    aoscici2000
        5
    aoscici2000  
    OP
       2019-12-23 21:31:39 +08:00
    @CzaOrz 大概懂了, 谢谢哈
    676529483
        6
    676529483  
       2019-12-23 22:44:02 +08:00
    单次调用肯定没区别啊,执行次数越多,优势越大
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:36 · PVG 07:36 · LAX 16:36 · JFK 19:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.