mpp_lock.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2021 Rockchip Electronics Co. LTD
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define MODULE_TAG "mpp_lock"
  17. #include "mpp_env.h"
  18. #include "mpp_log.h"
  19. #include "mpp_lock.h"
  20. #include "mpp_time.h"
  21. #define LOCK_IDLE 0
  22. #define LOCK_BUSY 1
  23. void mpp_spinlock_init(spinlock_t *lock)
  24. {
  25. MPP_SYNC_CLR(&lock->lock);
  26. lock->count = 0;
  27. lock->time = 0;
  28. mpp_env_get_u32("mpp_lock_debug", &lock->debug, 0);
  29. }
  30. void mpp_spinlock_lock(spinlock_t *lock)
  31. {
  32. RK_S64 time = 0;
  33. if (lock->debug)
  34. time = mpp_time();
  35. while (!MPP_BOOL_CAS(&lock->lock, LOCK_IDLE, LOCK_BUSY)) {
  36. asm("NOP");
  37. asm("NOP");
  38. }
  39. if (lock->debug && time) {
  40. lock->time += mpp_time() - time;
  41. lock->count++;
  42. }
  43. }
  44. void mpp_spinlock_deinit(spinlock_t *lock, const char *name)
  45. {
  46. if (lock->debug && lock->count) {
  47. mpp_log("lock %s lock %lld times take time %lld avg %d", name,
  48. lock->count, lock->time, (RK_S32)(lock->time / lock->count));
  49. }
  50. }
  51. void mpp_spinlock_unlock(spinlock_t *lock)
  52. {
  53. MPP_SYNC_CLR(&lock->lock);
  54. }
  55. bool mpp_spinlock_trylock(spinlock_t *lock)
  56. {
  57. RK_S64 time = 0;
  58. bool ret;
  59. if (lock->debug)
  60. time = mpp_time();
  61. ret = MPP_BOOL_CAS(&lock->lock, LOCK_IDLE, LOCK_BUSY);
  62. if (ret && lock->debug && time) {
  63. lock->time += mpp_time() - time;
  64. lock->count++;
  65. }
  66. return ret;
  67. }