You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.3KB

  1. #pragma once
  2. // Include most of the C standard library for convenience
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <stdint.h>
  6. #include <assert.h>
  7. #include <string>
  8. #include <condition_variable>
  9. #include <mutex>
  10. /** Surrounds raw text with quotes
  11. Example:
  12. printf("Hello " STRINGIFY(world))
  13. will expand to
  14. printf("Hello " "world")
  15. and of course the C++ lexer/parser will then concatenate the string literals
  16. */
  17. #define STRINGIFY(x) #x
  18. /** Converts a macro to a string literal
  19. Example:
  20. #define NAME "world"
  21. printf("Hello " TOSTRING(NAME))
  22. will expand to
  23. printf("Hello " "world")
  24. */
  25. #define TOSTRING(x) STRINGIFY(x)
  26. #define LENGTHOF(arr) (sizeof(arr) / sizeof((arr)[0]))
  27. /** Reserve space for _count enums starting with _name.
  28. Example:
  29. enum Foo {
  30. ENUMS(BAR, 14)
  31. };
  32. BAR + 0 to BAR + 11 is reserved
  33. */
  34. #define ENUMS(_name, _count) _name, _name ## _LAST = _name + (_count) - 1
  35. /** Deprecation notice for GCC */
  36. #define DEPRECATED __attribute__ ((deprecated))
  37. namespace rack {
  38. /** C#-style property constructor
  39. Example:
  40. Foo *foo = construct<Foo>(&Foo::greeting, "Hello world");
  41. */
  42. template<typename T>
  43. T *construct() {
  44. return new T();
  45. }
  46. template<typename T, typename F, typename V, typename... Args>
  47. T *construct(F f, V v, Args... args) {
  48. T *o = construct<T>(args...);
  49. o->*f = v;
  50. return o;
  51. }
  52. ////////////////////
  53. // Thread functions
  54. ////////////////////
  55. /** Threads which obtain a VIPLock will cause wait() to block for other less important threads.
  56. This does not provide the VIPs with an exclusive lock. That should be left up to another mutex shared between the less important thread.
  57. */
  58. struct VIPMutex {
  59. int count = 0;
  60. std::condition_variable cv;
  61. std::mutex countMutex;
  62. /** Blocks until there are no remaining VIPLocks */
  63. void wait() {
  64. std::unique_lock<std::mutex> lock(countMutex);
  65. while (count > 0)
  66. cv.wait(lock);
  67. }
  68. };
  69. struct VIPLock {
  70. VIPMutex &m;
  71. VIPLock(VIPMutex &m) : m(m) {
  72. std::unique_lock<std::mutex> lock(m.countMutex);
  73. m.count++;
  74. }
  75. ~VIPLock() {
  76. std::unique_lock<std::mutex> lock(m.countMutex);
  77. m.count--;
  78. lock.unlock();
  79. m.cv.notify_all();
  80. }
  81. };
  82. ////////////////////
  83. // logger
  84. ////////////////////
  85. extern FILE *gLogFile;
  86. void debug(const char *format, ...);
  87. void info(const char *format, ...);
  88. void warn(const char *format, ...);
  89. void fatal(const char *format, ...);
  90. } // namespace rack