Critical.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #pragma once
  2. #include <condition_variable>
  3. #include <initializer_list>
  4. #include "OperatingSystem.h"
  5. namespace Framework
  6. {
  7. class Thread;
  8. class Critical
  9. {
  10. private:
  11. CRITICAL_SECTION cs;
  12. Thread* owner;
  13. int lockCount;
  14. int id;
  15. public:
  16. //! Constructor
  17. DLLEXPORT Critical();
  18. //! Destructor
  19. DLLEXPORT ~Critical();
  20. //! Locks the object
  21. DLLEXPORT void lock();
  22. //! Tries to lock the object
  23. DLLEXPORT bool tryLock();
  24. //! Unlocks the object
  25. DLLEXPORT void unlock();
  26. //! Returns true if the object is locked
  27. DLLEXPORT bool isLocked() const;
  28. //! Returns a pointer to the thread that locked the object
  29. DLLEXPORT const Thread* zOwner() const;
  30. };
  31. class CriticalLock
  32. {
  33. private:
  34. Critical** criticals;
  35. int size;
  36. public:
  37. DLLEXPORT CriticalLock(std::initializer_list<Critical*> criticals);
  38. DLLEXPORT ~CriticalLock();
  39. };
  40. #define LOCK(x) CriticalLock _lock(x)
  41. #define LOCKN(x, i) CriticalLock _lock_##i(x)
  42. class Synchronizer
  43. {
  44. private:
  45. std::condition_variable block;
  46. std::mutex mutex;
  47. int numWaiting;
  48. bool skip;
  49. public:
  50. DLLEXPORT Synchronizer();
  51. DLLEXPORT ~Synchronizer();
  52. DLLEXPORT bool wait();
  53. DLLEXPORT bool wait(int milisec);
  54. DLLEXPORT void notify();
  55. DLLEXPORT void notify(int amount);
  56. DLLEXPORT void notifyAll();
  57. DLLEXPORT int getNumberOfWaitingThreads() const;
  58. };
  59. class Lock
  60. {
  61. public:
  62. virtual void lock() = 0;
  63. virtual bool tryLock() = 0;
  64. virtual void unlock() = 0;
  65. };
  66. class InternalReadLock;
  67. class InternalWriteLock;
  68. class ReadWriteLock
  69. {
  70. private:
  71. int* readerThreads;
  72. int* readCounters;
  73. int maxSize;
  74. int readerThreadCount;
  75. int writerThread;
  76. int writerCount;
  77. int waitingReaders;
  78. int waitingWriters;
  79. Critical cs;
  80. Synchronizer readerBlock;
  81. Synchronizer writerBlock;
  82. InternalReadLock* readLock;
  83. InternalWriteLock* writeLock;
  84. public:
  85. DLLEXPORT ReadWriteLock(int initialMaxSize = 10);
  86. DLLEXPORT ~ReadWriteLock();
  87. DLLEXPORT void lockRead();
  88. DLLEXPORT void lockWrite();
  89. DLLEXPORT void unlockRead();
  90. DLLEXPORT void unlockWrite();
  91. DLLEXPORT bool tryLockRead();
  92. DLLEXPORT bool tryLockWrite();
  93. DLLEXPORT Lock& getReadLock() const;
  94. DLLEXPORT Lock& getWriteLock() const;
  95. };
  96. } // namespace Framework