atomic_win32.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include "common/common.h"
  6. #include <intrin.h>
  7. #include <Windows.h>
  8. // Atomic operations are performed in a single step by the CPU. It is
  9. // impossible for other threads to see the operation "half-done."
  10. //
  11. // Some atomic operations can be combined with different types of memory
  12. // barriers called "Acquire semantics" and "Release semantics", defined below.
  13. //
  14. // Acquire semantics: Future memory accesses cannot be relocated to before the
  15. // operation.
  16. //
  17. // Release semantics: Past memory accesses cannot be relocated to after the
  18. // operation.
  19. //
  20. // These barriers affect not only the compiler, but also the CPU.
  21. //
  22. // NOTE: Acquire and Release are not differentiated right now. They perform a
  23. // full memory barrier instead of a "one-way" memory barrier. The newest
  24. // Windows SDK has Acquire and Release versions of some Interlocked* functions.
  25. namespace Common
  26. {
  27. inline void AtomicAdd(volatile u32& target, u32 value) {
  28. InterlockedExchangeAdd((volatile LONG*)&target, (LONG)value);
  29. }
  30. inline void AtomicAnd(volatile u32& target, u32 value) {
  31. _InterlockedAnd((volatile LONG*)&target, (LONG)value);
  32. }
  33. inline void AtomicIncrement(volatile u32& target) {
  34. InterlockedIncrement((volatile LONG*)&target);
  35. }
  36. inline void AtomicDecrement(volatile u32& target) {
  37. InterlockedDecrement((volatile LONG*)&target);
  38. }
  39. inline u32 AtomicLoad(volatile u32& src) {
  40. return src; // 32-bit reads are always atomic.
  41. }
  42. inline u32 AtomicLoadAcquire(volatile u32& src) {
  43. u32 result = src; // 32-bit reads are always atomic.
  44. _ReadBarrier(); // Compiler instruction only. x86 loads always have acquire semantics.
  45. return result;
  46. }
  47. inline void AtomicOr(volatile u32& target, u32 value) {
  48. _InterlockedOr((volatile LONG*)&target, (LONG)value);
  49. }
  50. inline void AtomicStore(volatile u32& dest, u32 value) {
  51. dest = value; // 32-bit writes are always atomic.
  52. }
  53. inline void AtomicStoreRelease(volatile u32& dest, u32 value) {
  54. _WriteBarrier(); // Compiler instruction only. x86 stores always have release semantics.
  55. dest = value; // 32-bit writes are always atomic.
  56. }
  57. }