asynchronous programming in python

前端 未结 6 1794
醉梦人生
醉梦人生 2020-11-29 18:21

Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matt

6条回答
  •  旧巷少年郎
    2020-11-29 19:00

    The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop.

    Here is a contrived example that would demonstrate using the threading module:

    from threading import Thread
    
    def background_stuff():
      while True:
        print "I am doing some stuff"
    
    t = Thread(target=background_stuff)
    t.start()
    
    # Continue doing some other stuff now
    

    However, in pretty much every useful case, you will want to communicate between threads. You should look into synchronization primitives, and become familiar with the concept of concurrency and the related issues.

    The threading module provides many such primitives for you to use, if you know how to use them.

提交回复
热议问题