11use std:: thread;
22
3- use clap:: { App , Arg } ;
3+ use clap:: Parser ;
44use shared_memory:: * ;
55
6+ /// Spawns N threads that increment a value to 100
7+ #[ derive( Parser ) ]
8+ #[ clap( author, version, about) ]
9+ struct Args {
10+ /// Number of threads to spawn
11+ num_threads : usize ,
12+
13+ /// Count to this value
14+ #[ clap( long, short, default_value_t = 50 ) ]
15+ count_to : u8 ,
16+ }
17+
618fn main ( ) {
719 env_logger:: init ( ) ;
20+ let args = Args :: parse ( ) ;
821
9- // Get number of thread argument
10- let matches = App :: new ( "Basic Example" )
11- . about ( "Spawns N threads that increment a value to 100" )
12- . arg (
13- Arg :: with_name ( "num_threads" )
14- . help ( "Number of threads to spawn" )
15- . required ( true )
16- . takes_value ( true ) ,
17- )
18- . get_matches ( ) ;
19- let num_threads: usize = matches
20- . value_of ( "num_threads" )
21- . unwrap ( )
22- . parse ( )
23- . expect ( "Invalid number passed for num_threads" ) ;
24- if num_threads < 1 {
22+ if args. num_threads < 1 {
2523 eprintln ! ( "Invalid number of threads" ) ;
2624 return ;
2725 }
2826
29- let mut threads = Vec :: with_capacity ( num_threads) ;
27+ let mut threads = Vec :: with_capacity ( args . num_threads ) ;
3028 let _ = std:: fs:: remove_file ( "basic_mapping" ) ;
31-
29+ let max = args . count_to ;
3230 // Spawn N threads
33- for i in 0 ..num_threads {
31+ for i in 0 ..args . num_threads {
3432 let thread_id = i + 1 ;
3533 threads. push ( thread:: spawn ( move || {
36- increment_value ( "basic_mapping" , thread_id) ;
34+ increment_value ( "basic_mapping" , thread_id, max ) ;
3735 } ) ) ;
3836 }
3937
@@ -44,7 +42,7 @@ fn main() {
4442}
4543
4644/// Increments a value that lives in shared memory
47- fn increment_value ( shmem_flink : & str , thread_num : usize ) {
45+ fn increment_value ( shmem_flink : & str , thread_num : usize , max : u8 ) {
4846 // Create or open the shared memory mapping
4947 let shmem = match ShmemConf :: new ( ) . size ( 4096 ) . flink ( shmem_flink) . create ( ) {
5048 Ok ( m) => m,
@@ -63,7 +61,7 @@ fn increment_value(shmem_flink: &str, thread_num: usize) {
6361
6462 // WARNING: This is prone to race conditions as no sync/locking is used
6563 unsafe {
66- while std:: ptr:: read_volatile ( raw_ptr) < 100 {
64+ while std:: ptr:: read_volatile ( raw_ptr) < max {
6765 // Increment shared value by one
6866 * raw_ptr += 1 ;
6967
0 commit comments