推荐学习书目
› 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 · Dec 29, 2018 · 2910 views
    This topic created in 2826 days ago, the information mentioned may be changed or developed.
    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 replies  •  2019-01-02 22:42:32 +08:00
    neoblackcap
        1
    neoblackcap  
       Dec 29, 2018 via iPhone
    例子会有创建孤儿进程的可能
    neoblackcap
        2
    neoblackcap  
       Dec 29, 2018
    订正,例子应该是不会有问题的
    shiyanfei5
        3
    shiyanfei5  
       Jan 2, 2019
    这不就相当于多开了一个线程跑这个函数么。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   865 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 21:08 · PVG 05:08 · LAX 14:08 · JFK 17:08
    ♥ Do have faith in what you're doing.