tvgLock.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2024 the ThorVG project. All rights reserved.
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. * The above copyright notice and this permission notice shall be included in all
  10. * copies or substantial portions of the Software.
  11. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. * SOFTWARE.
  18. */
  19. #ifndef _TVG_LOCK_H_
  20. #define _TVG_LOCK_H_
  21. #ifdef THORVG_THREAD_SUPPORT
  22. #include <mutex>
  23. #include "tvgTaskScheduler.h"
  24. namespace tvg {
  25. struct Key
  26. {
  27. std::mutex mtx;
  28. };
  29. struct ScopedLock
  30. {
  31. Key* key = nullptr;
  32. ScopedLock(Key& k)
  33. {
  34. if (TaskScheduler::threads() > 0) {
  35. k.mtx.lock();
  36. key = &k;
  37. }
  38. }
  39. ~ScopedLock()
  40. {
  41. if (TaskScheduler::threads() > 0) {
  42. key->mtx.unlock();
  43. }
  44. }
  45. };
  46. }
  47. #else //THORVG_THREAD_SUPPORT
  48. namespace tvg {
  49. struct Key {};
  50. struct ScopedLock
  51. {
  52. ScopedLock(Key& key) {}
  53. };
  54. }
  55. #endif //THORVG_THREAD_SUPPORT
  56. #endif //_TVG_LOCK_H_