Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
- Clojure
- C++
- C++
- C#
- C#
- D
- Dart
- Fortran
- Fortran
- Go
- Haskell
- JS
- Java
- Java
- Java
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
(def x (atom 0))
(def f inc)
(swap! x f)
std::atomic<int> x{};
auto local_x = x.load();
while(!x.compare_exchange_strong(local_x, f(local_x))) {
local_x = x.load();
}
I'm a bit unclear on whether the example is asking for an atomic value or something projected with a lock; I've shown an atomic.
private readonly object m_Sync = new object();
lock(m_Sync)
{
x = f(x);
}
synchronized x = f(x);
The synchronized statement can also be written with braces, but for one liners, they can be omitted.
The synchronized statement automatically wraps what ever is in it in a mutex.
The synchronized statement automatically wraps what ever is in it in a mutex.
x = f(x);
Dart is single-threaded. Other threads run in separate isolates.
x = f(x)
This is for a normal variable. In Fortran, normal variables which are not coarrays cannot be changed by another image.
integer, dimension[*] :: x
critical
x = f(x)
end critical
This is for a coarray scalar variable, which could be changed by another image.
let x = f(x)
JavaScript is single threaded, so we can be sure that no other thread will modify x in between :3
synchronized(lock){
x = f(x);
}
With this idiom, you have to manually ensure that any thread modifying x is guarded by the same lock object.
volatile T x;
"Atomic" access.
class Example<T> {
T x;
Object lock = new Object();
T read() {
synchronized (lock) {
return x;
}
}
void write(T x) {
synchronized (lock) {
this.x = x;
}
}
}
"Synchronized" access.
$mutex = Mutex::create();
Mutex::lock($mutex);
$x = f($x);
Mutex::unlock($mutex);
Mutex::destroy($mutex);
Warning
The Mutex class has been removed in pthreads v3.
The Mutex class has been removed in pthreads v3.
my $x :shared;
$x = 0;
sub my_task {
my $id = shift;
for (1 .. 5) {
sleep 2*rand();
{ # lock scope
lock($x);
print "thread $id found $x\n";
$x = $id;
sleep 2*rand();
}
}
}
threads->create('my_task', $_) for 1 .. 3;
sleep 5 while threads->list(threads::running);
lock is lexically scoped. Delay outside the lock scope allows other threads a chance at changing $x.