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
jstony
V2EX  ›  Python

如何调用一个 function 而不用等待其返回

  •  
  •   jstony · 2021-09-24 17:54:36 +08:00 · 3288 次点击
    这是一个创建于 916 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如现在有两个 function,一个 fun a,一个 fun b,在 fun a 中需要调用 fun b,但是对 b 的执行结果毫不关心,也不用等待 b 执行完,怎么实现比较合适?
    11 条回复    2021-09-25 02:35:01 +08:00
    wd
        1
    wd  
       2021-09-24 17:56:17 +08:00 via iPhone
    async 或者线程
    kealm
        2
    kealm  
       2021-09-24 18:02:52 +08:00
    ```js
    async function b() {
    return new Promise((resolve) => setTimeout(resolve, 10000))
    }

    function a() {
    console.time('b')
    b()
    console.timeEnd('b')
    }

    async function aa() {
    console.time('b')
    await b()
    console.timeEnd('b')
    }
    ```
    ila
        3
    ila  
       2021-09-24 18:08:06 +08:00 via Android
    celery
    Abbeyok
        4
    Abbeyok  
       2021-09-24 18:12:28 +08:00 via Android
    threading.Thread
    rootit
        5
    rootit  
       2021-09-24 18:18:19 +08:00
    python 肯定首选 asyncio.create_task() 了,再次 threading 起线程
    deplivesb
        6
    deplivesb  
       2021-09-24 19:11:18 +08:00
    了解一下异步
    demonzoo
        7
    demonzoo  
       2021-09-24 20:34:08 +08:00
    就直接在 a 里面调用 b() 就好了啊。。。不要 await b()
    IsaacYoung
        8
    IsaacYoung  
       2021-09-24 20:34:31 +08:00
    thread
    meiyoumingzi6
        9
    meiyoumingzi6  
       2021-09-24 21:24:45 +08:00
    哈哈哈哈哈哈 我当时刚接触 python 的时候也思考过这个问题

    0. 多线程, 把 b 丢进新的线程计算
    1. 多进程, 同上
    3. 协程 async
    4. celcry 等异步框架
    5. 换 golang, 无脑 go 就行了 [手动狗头
    yianing
        10
    yianing  
       2021-09-25 02:15:23 +08:00 via Android
    golang:go 就完了
    dangyuluo
        11
    dangyuluo  
       2021-09-25 02:35:01 +08:00
    这种情况 Async 比多线程要好
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5401 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 06:48 · PVG 14:48 · LAX 23:48 · JFK 02:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.