mutex.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2021-04-27 flybreak the first version.
  9. */
  10. #include "mutex"
  11. namespace std
  12. {
  13. // use a set of global and static objects
  14. // a proxy function to pthread_once
  15. function<void()> once_functor;
  16. mutex& get_once_mutex()
  17. {
  18. static mutex once_mutex;
  19. return once_mutex;
  20. }
  21. inline unique_lock<mutex>*& get_once_functor_lock_ptr()
  22. {
  23. static unique_lock<mutex>* once_functor_mutex_ptr = nullptr;
  24. return once_functor_mutex_ptr;
  25. }
  26. void set_once_functor_lock_ptr(unique_lock<mutex>* m_ptr)
  27. {
  28. get_once_functor_lock_ptr() = m_ptr;
  29. }
  30. extern "C"
  31. {
  32. void once_proxy()
  33. {
  34. // need to first transfer the functor's ownership so as to call it
  35. function<void()> once_call = std::move(once_functor);
  36. // no need to hold the lock anymore
  37. unique_lock<mutex>* lock_ptr = get_once_functor_lock_ptr();
  38. get_once_functor_lock_ptr() = nullptr;
  39. lock_ptr->unlock();
  40. once_call();
  41. }
  42. }
  43. }