Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Async: ways to store state


Published on

Async: ways to store state

Published in: Software
  • Be the first to comment

  • Be the first to like this

Async: ways to store state

  1. 1. Async: ways to store state 果凍
  2. 2. Intro The slide is for “What Is Async, How Does It Work, & When Should I Use It? by A. Jesse Jiryu Davis” p14
  3. 3. Threading
  4. 4. Callback def func(): print 'finish' something.on_finish(callback=func)
  5. 5. Coroutines import asyncio @asyncio.coroutine def compute(x, y): print("Compute %s + %s ..." % (x, y)) yield from asyncio.sleep(1.0) return x + y
  6. 6. Coroutines @asyncio.coroutine def print_sum(x, y): result = yield from compute(x, y) print("%s + %s = %s" % (x, y, result)) loop = asyncio.get_event_loop() loop.run_until_complete(print_sum(1, 2)) loop.close()
  7. 7. Coroutines
  8. 8. Greenlets skip
  9. 9. Fibers import fibers def func1(): print "1" f2.switch() print "3" f2.switch() f1 = fibers.Fiber (target=func1) f2 = fibers.Fiber (target=func2) f1.switch() def func2(): print "2" f1.switch() print "4"
  10. 10. Actor model ● When an actor receives a message it may take actions like: ○ altering its own state, e.g. so that it can react differently to a future message, ○ sending messages to other actors, or ○ starting new actors. ● None of the actions are required, and they may be applied in any order.
  11. 11. Actor model ● An actor is an execution unit that executes concurrently with other actors. ● An actor does not share state with anybody else, but it can have its own state. ● An actor can only communicate with other actors by sending and receiving messages. It can only send messages to actors whose address it has.
  12. 12. Actor model ● An actor only processes one message at a time. In other words, a single actor does not give you any concurrency, and it does not need to use locks internally to protect its own state.
  13. 13. Actor model import pykka class Greeter(pykka.ThreadingActor): def __init__(self, greeting='Hi there!'): super(Greeter, self).__init__() self.greeting = greeting def on_receive(self, message): print(self.greeting)
  14. 14. Actor model actor_ref = Greeter.start(greeting='Hi you!') actor_ref.tell({'msg': 'Hi!'}) # => Returns nothing. Will never block. answer = actor_ref.ask({'msg': 'Hi?'}) # => May block forever waiting for an answer
  15. 15. Actor model answer = actor_ref.ask({'msg': 'Hi?'}, timeout=3) # => May wait 3s for an answer, then raises exception if no answer.
  16. 16. Actor model future = actor_ref.ask({'msg': 'Hi?'}, block=False) # => Will return a future object immediately. answer = future.get() # => May block forever waiting for an answer answer = future.get(timeout=0.1) # => May wait 0.1s for an answer, then raises exception if no answer.