@@ -359,6 +359,8 @@ println!("test_map_reduce_filter Result is {:?}", result);
359
359
360
360
## Actor
361
361
362
+ ### Actor common(send/receive/spawn/states)
363
+
362
364
Example:
363
365
364
366
``` rust
@@ -475,3 +477,74 @@ assert_eq!(
475
477
v . as_slice ()
476
478
)
477
479
```
480
+
481
+ ### Actor Ask (inspired by Akka/Erlang)
482
+
483
+ Example:
484
+
485
+ ``` rust
486
+ use std :: time :: Duration ;
487
+
488
+ use fp_rust :: common :: LinkedListAsync ;
489
+
490
+ #[derive(Clone , Debug )]
491
+ enum Value {
492
+ AskIntByLinkedListAsync ((i32 , LinkedListAsync <i32 >)),
493
+ AskIntByBlockingQueue ((i32 , BlockingQueue <i32 >)),
494
+ }
495
+
496
+ let mut root = ActorAsync :: new (
497
+ move | _ : & mut ActorAsync <_ , _ >, msg : Value , _ : & mut HashMap <String , Value >| match msg {
498
+ Value :: AskIntByLinkedListAsync (v ) => {
499
+ println! (" Actor AskIntByLinkedListAsync" );
500
+ v . 1. push_back (v . 0 * 10 );
501
+ }
502
+ Value :: AskIntByBlockingQueue (mut v ) => {
503
+ println! (" Actor AskIntByBlockingQueue" );
504
+
505
+ // NOTE If negative, hanging for testing timeout
506
+ if v . 0 < 0 {
507
+ return ;
508
+ }
509
+
510
+ // NOTE General Cases
511
+ v . 1. offer (v . 0 * 10 );
512
+ } // _ => {}
513
+ },
514
+ );
515
+
516
+ let mut root_handle = root . get_handle ();
517
+ root . start ();
518
+
519
+ // LinkedListAsync<i32>
520
+ let result_i32 = LinkedListAsync :: <i32 >:: new ();
521
+ root_handle . send (Value :: AskIntByLinkedListAsync ((1 , result_i32 . clone ())));
522
+ root_handle . send (Value :: AskIntByLinkedListAsync ((2 , result_i32 . clone ())));
523
+ root_handle . send (Value :: AskIntByLinkedListAsync ((3 , result_i32 . clone ())));
524
+ thread :: sleep (Duration :: from_millis (1 ));
525
+ let i = result_i32 . pop_front ();
526
+ assert_eq! (Some (10 ), i );
527
+ let i = result_i32 . pop_front ();
528
+ assert_eq! (Some (20 ), i );
529
+ let i = result_i32 . pop_front ();
530
+ assert_eq! (Some (30 ), i );
531
+
532
+ // BlockingQueue<i32>
533
+ let mut result_i32 = BlockingQueue :: <i32 >:: new ();
534
+ result_i32 . timeout = Some (Duration :: from_millis (1 ));
535
+ root_handle . send (Value :: AskIntByBlockingQueue ((4 , result_i32 . clone ())));
536
+ root_handle . send (Value :: AskIntByBlockingQueue ((5 , result_i32 . clone ())));
537
+ root_handle . send (Value :: AskIntByBlockingQueue ((6 , result_i32 . clone ())));
538
+ thread :: sleep (Duration :: from_millis (1 ));
539
+ let i = result_i32 . take ();
540
+ assert_eq! (Some (40 ), i );
541
+ let i = result_i32 . take ();
542
+ assert_eq! (Some (50 ), i );
543
+ let i = result_i32 . take ();
544
+ assert_eq! (Some (60 ), i );
545
+
546
+ // Timeout case:
547
+ root_handle . send (Value :: AskIntByBlockingQueue ((- 1 , result_i32 . clone ())));
548
+ let i = result_i32 . take ();
549
+ assert_eq! (None , i );
550
+ ```
0 commit comments