MCPcopy Create free account
hub / github.com/elast0ny/shared_memory / increment_value

Function increment_value

examples/basic.rs:45–78  ·  view source on GitHub ↗

Increments a value that lives in shared memory

(shmem_flink: &str, thread_num: usize, max: u8)

Source from the content-addressed store, hash-verified

43
44/// Increments a value that lives in shared memory
45fn 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}

Callers 1

mainFunction · 0.70

Calls 5

createMethod · 0.80
flinkMethod · 0.80
sizeMethod · 0.80
openMethod · 0.80
as_ptrMethod · 0.80

Tested by

no test coverage detected