1114. 按序打印

要按顺序打印,并且保证不会出现思索。

  1. #include <semaphore.h>
  2. class Foo {
  3. protected:
  4. sem_t firstJobDone;//两个信号量
  5. sem_t secondJobDone;
  6. public:
  7. Foo() {
  8. sem_init(&firstJobDone, 0, 0);//初始值为0
  9. sem_init(&secondJobDone, 0, 0);
  10. }
  11. void first(function<void()> printFirst) {
  12. // printFirst() outputs "first".
  13. printFirst();//因为执行first不需要解锁,所以先执行
  14. sem_post(&firstJobDone);//解锁
  15. }
  16. void second(function<void()> printSecond) {
  17. sem_wait(&firstJobDone);//加锁
  18. // printSecond() outputs "second".
  19. printSecond();
  20. sem_post(&secondJobDone);
  21. }
  22. void third(function<void()> printThird) {
  23. sem_wait(&secondJobDone);
  24. // printThird() outputs "third".
  25. printThird();
  26. }
  27. };