Memory barry
memory barry fence 有两种形式,一种叫做full-fence 一种叫做half-fence
volitile是一种half-fence
The volatile keyword instructs the compiler to generate an acquire-fence _on every read from that field, and a release-fence _on every write to that field. An acquire-fence prevents other reads/writes from being moved _before _the fence; a release-fence prevents other reads/writes from being moved _after _the fence. These “half-fences” are faster than full fences because they give the runtime and hardware more scope for optimization.
static void Main(){bool complete = false;var t = new Thread (() =>{bool toggle = false;while (!complete) toggle = !toggle;});t.Start();Thread.Sleep (1000);complete = true;t.Join(); // Blocks indefinitely}
Interlocked
原子操作,多线程在32位机器上读写long(Int64)时可能会造成数据撕裂(读前32位之后写了该数据,导致结果变成了新32位加旧32位)。
Wait and Pulse
Monitor.Wait 和Monitor.Pulse获取锁,释放锁,再此获取锁的小技巧
class SimpleWaitPulse{static readonly object _locker = new object();static bool _go;static void Main(){ // The new thread will blocknew Thread (Work).Start(); // because _go==false.Console.ReadLine(); // Wait for user to hit Enterlock (_locker) // Let's now wake up the thread by{ // setting _go=true and pulsing._go = true;Monitor.Pulse (_locker);}}static void Work(){lock (_locker)while (!_go)Monitor.Wait (_locker); // Lock is released while we’re waitingConsole.WriteLine ("Woken!!!");}}
