Increments a value that lives in shared memory
(shmem_flink: &str, thread_num: usize, max: u8)
| 43 | |
| 44 | /// Increments a value that lives in shared memory |
| 45 | fn increment_value(shmem_flink: &str, thread_num: usize, max: u8) { |
| 46 | // Create or open the shared memory mapping |
| 47 | let shmem = match ShmemConf::new().size(4096).flink(shmem_flink).create() { |
| 48 | Ok(m) => m, |
| 49 | Err(ShmemError::LinkExists) => ShmemConf::new().flink(shmem_flink).open().unwrap(), |
| 50 | Err(e) => { |
| 51 | eprintln!( |
| 52 | "Unable to create or open shmem flink {} : {}", |
| 53 | shmem_flink, e |
| 54 | ); |
| 55 | return; |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | // Get pointer to the shared memory |
| 60 | let raw_ptr = shmem.as_ptr(); |
| 61 | |
| 62 | // WARNING: This is prone to race conditions as no sync/locking is used |
| 63 | unsafe { |
| 64 | while std::ptr::read_volatile(raw_ptr) < max { |
| 65 | // Increment shared value by one |
| 66 | *raw_ptr += 1; |
| 67 | |
| 68 | println!( |
| 69 | "[thread:{}] {}", |
| 70 | thread_num, |
| 71 | std::ptr::read_volatile(raw_ptr) |
| 72 | ); |
| 73 | |
| 74 | // Sleep for a bit |
| 75 | std::thread::sleep(std::time::Duration::from_secs(1)); |
| 76 | } |
| 77 | } |
| 78 | } |