ThreadingUtil.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright 2008, Yahoo! Inc.
  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. #include <sys/types.h>
  17. #include "ThreadingUtil.h"
  18. #include "LibCSymTable.h"
  19. #ifdef THREADED
  20. // ****************************************************************************
  21. // Mutex wrapper
  22. struct Mutex::Impl{
  23. Impl(){
  24. LIBC_SYMBOLS.pthread_mutex_init(&mut_, 0);
  25. }
  26. ~Impl(){
  27. LIBC_SYMBOLS.pthread_mutex_destroy(&mut_);
  28. }
  29. pthread_mutex_t mut_;
  30. };
  31. Mutex::Mutex():impl_(new Impl) {}
  32. Mutex::~Mutex() { delete impl_;}
  33. void Mutex::acquire() {
  34. LIBC_SYMBOLS.pthread_mutex_lock(&impl_->mut_);
  35. }
  36. void Mutex::release() {
  37. LIBC_SYMBOLS.pthread_mutex_unlock(&impl_->mut_);
  38. }
  39. // ****************************************************************************
  40. // Atomics
  41. int32_t atomic_post_incr(volatile int32_t* operand, int32_t incr)
  42. {
  43. int32_t result;
  44. __asm__ __volatile__(
  45. "lock xaddl %0,%1\n"
  46. : "=r"(result), "=m"(*operand)
  47. : "0"(incr)
  48. : "memory");
  49. return result;
  50. }
  51. int32_t atomic_fetch_store(volatile int32_t *ptr, int32_t value)
  52. {
  53. int32_t result;
  54. __asm__ __volatile__("lock xchgl %0,%1\n"
  55. : "=r"(result), "=m"(*ptr)
  56. : "0"(value)
  57. : "memory");
  58. return result;
  59. }
  60. #else
  61. int32_t atomic_post_incr(volatile int32_t* operand, int32_t incr){
  62. int32_t v=*operand;
  63. *operand+=incr;
  64. return v;
  65. }
  66. int32_t atomic_fetch_store(volatile int32_t *ptr, int32_t value)
  67. {
  68. int32_t result=*ptr;
  69. *ptr=value;
  70. return result;
  71. }
  72. #endif // THREADED