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

线程装饰器,实现异步

  •  
  •   fanhaipeng0403 · 2018-12-29 18:26:24 +08:00 · 1914 次点击
    这是一个创建于 1917 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import time
    def run_async(func):
        from threading import Thread
        from functools import wraps
        @wraps(func)
        def async_func(*args, **kwargs):
            func_hl = Thread(target = func, args = args, kwargs = kwargs)
            func_hl.start()
            # func_hl.join(),  阻塞主进程(挡住,无法执行 join 以后的语句),专注执行多线程。
            # func_hl.join(2), 设置参数后,则等待该线程这么长时间就不管它了(而该线程并没有结束)。不管的意思就是可以执行后面的主进程了。
            return func_hl
        return async_func
    
    @run_async
    def child():
        time.sleep(4)
        print('thread child')
    
    @run_async
    def child1():
        time.sleep(2)
        print('thread child1')
    
    def main():
        child()
        child1()
        print('Done')
    

    In [27]: main() Done

    In [28]: thread child1 thread child

    3 条回复    2019-01-02 22:42:32 +08:00
    neoblackcap
        1
    neoblackcap  
       2018-12-29 19:53:23 +08:00 via iPhone
    例子会有创建孤儿进程的可能
    neoblackcap
        2
    neoblackcap  
       2018-12-29 20:08:16 +08:00
    订正,例子应该是不会有问题的
    shiyanfei5
        3
    shiyanfei5  
       2019-01-02 22:42:32 +08:00
    这不就相当于多开了一个线程跑这个函数么。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2790 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:44 · PVG 22:44 · LAX 07:44 · JFK 10:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.