mutex.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/common/mutex.h>
  6. #include <aws/common/posix/common.inl>
  7. #include <errno.h>
  8. void aws_mutex_clean_up(struct aws_mutex *mutex) {
  9. AWS_PRECONDITION(mutex);
  10. if (mutex->initialized) {
  11. pthread_mutex_destroy(&mutex->mutex_handle);
  12. }
  13. AWS_ZERO_STRUCT(*mutex);
  14. }
  15. int aws_mutex_init(struct aws_mutex *mutex) {
  16. AWS_PRECONDITION(mutex);
  17. pthread_mutexattr_t attr;
  18. int err_code = pthread_mutexattr_init(&attr);
  19. int return_code = AWS_OP_SUCCESS;
  20. if (!err_code) {
  21. if ((err_code = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)) ||
  22. (err_code = pthread_mutex_init(&mutex->mutex_handle, &attr))) {
  23. return_code = aws_private_convert_and_raise_error_code(err_code);
  24. }
  25. pthread_mutexattr_destroy(&attr);
  26. } else {
  27. return_code = aws_private_convert_and_raise_error_code(err_code);
  28. }
  29. mutex->initialized = (return_code == AWS_OP_SUCCESS);
  30. return return_code;
  31. }
  32. int aws_mutex_lock(struct aws_mutex *mutex) {
  33. AWS_PRECONDITION(mutex && mutex->initialized);
  34. return aws_private_convert_and_raise_error_code(pthread_mutex_lock(&mutex->mutex_handle));
  35. }
  36. int aws_mutex_try_lock(struct aws_mutex *mutex) {
  37. AWS_PRECONDITION(mutex && mutex->initialized);
  38. return aws_private_convert_and_raise_error_code(pthread_mutex_trylock(&mutex->mutex_handle));
  39. }
  40. int aws_mutex_unlock(struct aws_mutex *mutex) {
  41. AWS_PRECONDITION(mutex && mutex->initialized);
  42. return aws_private_convert_and_raise_error_code(pthread_mutex_unlock(&mutex->mutex_handle));
  43. }