1+ use dashmap:: DashMap ;
12use std:: sync:: Arc ;
23use std:: thread;
3- use dashmap:: DashMap ;
44
55pub fn hashmap_example ( ) {
66 let map = Arc :: new ( DashMap :: new ( ) ) ;
@@ -11,26 +11,97 @@ pub fn hashmap_example() {
1111 map1. insert ( 2 , 3 ) ;
1212 } ) ;
1313
14-
1514 let map2 = map. clone ( ) ;
1615 let rhandle = thread:: spawn ( move || {
17-
1816 loop {
1917 if let Some ( v) = map2. get ( & 1 ) {
2018 println ! ( "get value {} for key 1" , * v) ;
2119 break ;
22- }
20+ }
2321 }
2422
2523 loop {
2624 if let Some ( v) = map2. get ( & 2 ) {
2725 println ! ( "get value {} for key 2" , * v) ;
2826 break ;
29- }
27+ }
3028 }
3129 } ) ;
3230
3331 whandle. join ( ) . unwrap ( ) ;
3432 rhandle. join ( ) . unwrap ( ) ;
33+ }
34+
35+ pub fn flurry_hashmap ( ) {
36+ let map = flurry:: HashMap :: new ( ) ;
37+
38+ assert_eq ! ( map. pin( ) . insert( 37 , "a" ) , None ) ;
39+ assert_eq ! ( map. pin( ) . is_empty( ) , false ) ;
40+ }
41+
42+ pub fn flurry_hashset ( ) {
43+ // Initialize a new hash set.
44+ let books = flurry:: HashSet :: new ( ) ;
45+ let guard = books. guard ( ) ;
46+
47+ // Add some books
48+ books. insert ( "Fight Club" , & guard) ;
49+ books. insert ( "Three Men In A Raft" , & guard) ;
50+ books. insert ( "The Book of Dust" , & guard) ;
51+ books. insert ( "The Dry" , & guard) ;
52+
53+ // Check for a specific one.
54+ if !books. contains ( & "The Drunken Botanist" , & guard) {
55+ println ! ( "We don't have The Drunken Botanist." ) ;
56+ }
57+
58+ // Remove a book.
59+ books. remove ( & "Three Men In A Raft" , & guard) ;
60+
61+ // Iterate over everything.
62+ for book in books. iter ( & guard) {
63+ println ! ( "{}" , book) ;
64+ }
65+ }
66+
67+ pub fn evmap_example ( ) {
68+ let ( book_reviews_r, mut book_reviews_w) = evmap:: new ( ) ;
3569
70+ let readers: Vec < _ > = ( 0 ..4 )
71+ . map ( |_| {
72+ let r = book_reviews_r. clone ( ) ;
73+ thread:: spawn ( move || {
74+ loop {
75+ let l = r. len ( ) ;
76+ if l == 0 {
77+ thread:: yield_now ( ) ;
78+ } else {
79+ // the reader will either see all the reviews,
80+ // or none of them, since refresh() is atomic.
81+ assert_eq ! ( l, 4 ) ;
82+ break ;
83+ }
84+ }
85+ } )
86+ } )
87+ . collect ( ) ;
88+
89+ // do some writes
90+ book_reviews_w. insert ( "Adventures of Huckleberry Finn" , "My favorite book." ) ;
91+ book_reviews_w. insert ( "Grimms' Fairy Tales" , "Masterpiece." ) ;
92+ book_reviews_w. insert ( "Pride and Prejudice" , "Very enjoyable." ) ;
93+ book_reviews_w. insert ( "The Adventures of Sherlock Holmes" , "Eye lyked it alot." ) ;
94+ // expose the writes
95+ book_reviews_w. refresh ( ) ;
96+
97+ // you can read through the write handle
98+ assert_eq ! ( book_reviews_w. len( ) , 4 ) ;
99+
100+ // the original read handle still works too
101+ assert_eq ! ( book_reviews_r. len( ) , 4 ) ;
102+
103+ // all the threads should eventually see .len() == 4
104+ for r in readers. into_iter ( ) {
105+ assert ! ( r. join( ) . is_ok( ) ) ;
106+ }
36107}
0 commit comments