Critical.h 2.5 KB

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