Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. trait Actor<T> {
  2. pub fn new(inner: T, pool: &Pool) -> Actor<T>;
  3. pub fn sync<U>(&self, msg: FnOnce(&mut T)) -> U;
  4. pub fn async<U>(&self, msg: FnOnce(&mut T)) -> Future<U>;
  5. }
  6.  
  7. fn example() {
  8. // wake the main thread and create an actor on it
  9. let button = main_pool.sync(
  10. |pool| Actor::new(Button::new(), pool)
  11. );
  12.  
  13. // an actor handle can be cloned, and the actors life cycle is tied
  14. // the existance of these handles. When a handle dies, the actor is released.
  15. let sent_button = button.clone();
  16. thread::spawn(move || {
  17. // the handle is Send even if the actor's inner body is not. Meaning it can live
  18. // on other thread and safely talk to the actor if they choose to.
  19. let old_color = sent_button.sync(|button| {
  20. // we can talk to the button on the main thread, a sync block blocks the current
  21. // thread until the message is reponded to. But has the advantage of being simpler
  22. // and avoiding allocation that is required by a Box<FnOnce>
  23. let old_color = button.color();
  24. button.set_color(Color.red);
  25.  
  26. // data can be sent back if we choose to. This can help us fairy data too and from the actor
  27. old_color
  28. });
  29.  
  30. // we can also async send to the actor, meaning it needn't block. These are handled
  31. // as soon as possible by the main thread, but may need to wait for other IO to complete.
  32. let some_future = sent_button.async(|button| {
  33. button.set_color(old_color);
  34.  
  35. // it could be nice to self enqueue, since this is run in locked actor context
  36. // we can do a faster job of doing an async enqueue.
  37. after(|button| {
  38.  
  39. });
  40.  
  41. // also enqueue to the end of the queue, avoiding the fast path. Useful if you want
  42. // fair handling of actions.
  43. later(|button| {
  44.  
  45. });
  46.  
  47. // The API of those two are probably not possible, they will likely require a `Context` object
  48. // that will convay the types.
  49. });
  50. })
  51.  
  52. // It's important to point out that the locking model means only one function is every being
  53. // applied to the object.
  54. button.async(|button| {
  55.  
  56. });
  57.  
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement