Implementation
D

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating resource.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
synchronized(lock){
  x = f(x);
}
use threads;
use threads::shared;
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);
let mut x = x.lock().unwrap();
*x = f(x);
require 'atomic'
x = Atomic.new(0)
x.update { |x| f(x) }
import Control.Concurrent.MVar
putMVar x . f =<< takeMVar x
x = f(x);
import "sync"
var lock sync.RWMutex

lock.Lock()
x = f(x)
lock.Unlock()
import threading
lock = threading.Lock()

lock.acquire()
try:
	x = f(x)
finally:
	lock.release()
uses syncobjs;
var
  loc: TCriticalSection;
begin
  loc.Enter;
  try
    x := f(x);
  finally
    loc.Leave;
  end;
end.
$mutex = Mutex::create();
Mutex::lock($mutex);
$x = f($x);
Mutex::unlock($mutex);
Mutex::destroy($mutex);
let x = f(x)