Barrier.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  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. #ifndef ANDROID_BARRIER_H
  17. #define ANDROID_BARRIER_H
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include <utils/threads.h>
  21. namespace android {
  22. class Barrier
  23. {
  24. public:
  25. inline Barrier() : state(CLOSED) { }
  26. inline ~Barrier() { }
  27. // Release any threads waiting at the Barrier.
  28. // Provides release semantics: preceding loads and stores will be visible
  29. // to other threads before they wake up.
  30. void open() {
  31. Mutex::Autolock _l(lock);
  32. state = OPENED;
  33. cv.broadcast();
  34. }
  35. // Reset the Barrier, so wait() will block until open() has been called.
  36. void close() {
  37. Mutex::Autolock _l(lock);
  38. state = CLOSED;
  39. }
  40. // Wait until the Barrier is OPEN.
  41. // Provides acquire semantics: no subsequent loads or stores will occur
  42. // until wait() returns.
  43. void wait() const {
  44. Mutex::Autolock _l(lock);
  45. while (state == CLOSED) {
  46. cv.wait(lock);
  47. }
  48. }
  49. private:
  50. enum { OPENED, CLOSED };
  51. mutable Mutex lock;
  52. mutable Condition cv;
  53. volatile int state;
  54. };
  55. }; // namespace android
  56. #endif // ANDROID_BARRIER_H