@@ -293,4 +293,77 @@ mod tests {
293293 cached. set ( 100 ) ;
294294 assert_eq ! ( cached. get( ) , Some ( 100 ) ) ;
295295 }
296+
297+ #[ test]
298+ fn test_cache_concurrent_access ( ) {
299+ use std:: sync:: Arc ;
300+ use std:: thread;
301+
302+ let cache = Arc :: new ( LocatorCache :: < i32 , i32 > :: new ( ) ) ;
303+ let num_threads = 10 ;
304+ let operations_per_thread = 100 ;
305+
306+ // Spawn multiple threads that concurrently read and write
307+ let handles: Vec < _ > = ( 0 ..num_threads)
308+ . map ( |thread_id| {
309+ let cache = Arc :: clone ( & cache) ;
310+ thread:: spawn ( move || {
311+ for i in 0 ..operations_per_thread {
312+ let key = ( thread_id * operations_per_thread + i) % 50 ;
313+ // Mix of reads and writes
314+ if i % 2 == 0 {
315+ cache. insert ( key, thread_id * 1000 + i) ;
316+ } else {
317+ let _ = cache. get ( & key) ;
318+ }
319+ }
320+ } )
321+ } )
322+ . collect ( ) ;
323+
324+ // Wait for all threads to complete
325+ for handle in handles {
326+ handle. join ( ) . expect ( "Thread panicked" ) ;
327+ }
328+
329+ // Verify the cache is still functional after concurrent access
330+ cache. insert ( 999 , 999 ) ;
331+ assert_eq ! ( cache. get( & 999 ) , Some ( 999 ) ) ;
332+ }
333+
334+ #[ test]
335+ fn test_cached_value_concurrent_access ( ) {
336+ use std:: sync:: Arc ;
337+ use std:: thread;
338+
339+ let cached = Arc :: new ( CachedValue :: < i32 > :: new ( ) ) ;
340+ let num_threads = 10 ;
341+
342+ // Spawn multiple threads that concurrently try to compute/set values
343+ let handles: Vec < _ > = ( 0 ..num_threads)
344+ . map ( |thread_id| {
345+ let cached = Arc :: clone ( & cached) ;
346+ thread:: spawn ( move || {
347+ for i in 0 ..100 {
348+ if i % 3 == 0 {
349+ cached. set ( thread_id * 1000 + i) ;
350+ } else if i % 3 == 1 {
351+ let _ = cached. get ( ) ;
352+ } else {
353+ let _ = cached. get_or_compute ( || thread_id * 1000 + i) ;
354+ }
355+ }
356+ } )
357+ } )
358+ . collect ( ) ;
359+
360+ // Wait for all threads to complete
361+ for handle in handles {
362+ handle. join ( ) . expect ( "Thread panicked" ) ;
363+ }
364+
365+ // Verify the cached value is still accessible after concurrent access
366+ cached. set ( 12345 ) ;
367+ assert_eq ! ( cached. get( ) , Some ( 12345 ) ) ;
368+ }
296369}
0 commit comments