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.

  1. static void Main()
  2. {
  3. bool complete = false;
  4. var t = new Thread (() =>
  5. {
  6. bool toggle = false;
  7. while (!complete) toggle = !toggle;
  8. });
  9. t.Start();
  10. Thread.Sleep (1000);
  11. complete = true;
  12. t.Join(); // Blocks indefinitely
  13. }

Interlocked

原子操作,多线程在32位机器上读写long(Int64)时可能会造成数据撕裂(读前32位之后写了该数据,导致结果变成了新32位加旧32位)。

Wait and Pulse

Monitor.Wait 和Monitor.Pulse获取锁,释放锁,再此获取锁的小技巧

  1. class SimpleWaitPulse
  2. {
  3. static readonly object _locker = new object();
  4. static bool _go;
  5. static void Main()
  6. { // The new thread will block
  7. new Thread (Work).Start(); // because _go==false.
  8. Console.ReadLine(); // Wait for user to hit Enter
  9. lock (_locker) // Let's now wake up the thread by
  10. { // setting _go=true and pulsing.
  11. _go = true;
  12. Monitor.Pulse (_locker);
  13. }
  14. }
  15. static void Work()
  16. {
  17. lock (_locker)
  18. while (!_go)
  19. Monitor.Wait (_locker); // Lock is released while we’re waiting
  20. Console.WriteLine ("Woken!!!");
  21. }
  22. }