Logo

Programming-Idioms

History of Idiom 33 > diff from v5 to v6

Edit summary for version 6 by :

Version 5

2015-08-20, 18:16:31

Version 6

2015-08-21, 23:14:19

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Code
let mut x = x.lock().unwrap();
*x = f(x);
Code
let mut x = x.lock().unwrap();
*x = f(x);
Comments bubble
Assuming x is created like this:
`let x = Mutex::new(0);`
Comments bubble
Assuming x is created like this:
`let x = Mutex::new(0);`
Doc URL
http://doc.rust-lang.org/std/sync/struct.Mutex.html#examples
Origin
http://doc.rust-lang.org/std/sync/struct.Mutex.html#examples
Demo URL
https://play.rust-lang.org/?code=use%20std%3A%3Async%3A%3AMutex%3B%0A%0Afn%20f(x%3A%20i32)%20-%3E%20i32%20%7B%0A%20%20%20%20x%20%2B%201%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20x%20%3D%20Mutex%3A%3Anew(0)%3B%0A%20%20%20%20let%20mut%20x%20%3D%20x.lock().unwrap()%3B%0A%20%20%20%20*x%20%3D%20f(*x)%3B%0A%20%20%20%20%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20*x)%3B%0A%7D%0A&version=stable
Demo URL
https://play.rust-lang.org/?code=use%20std%3A%3Async%3A%3AMutex%3B%0A%0Afn%20f(x%3A%20i32)%20-%3E%20i32%20%7B%0A%20%20%20%20x%20%2B%201%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20x%20%3D%20Mutex%3A%3Anew(0)%3B%0A%20%20%20%20let%20mut%20x%20%3D%20x.lock().unwrap()%3B%0A%20%20%20%20*x%20%3D%20f(*x)%3B%0A%20%20%20%20%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20*x)%3B%0A%7D%0A&version=stable