BlockingSync.h 18.6 KB
Newer Older
Martin Karsten's avatar
Martin Karsten committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/******************************************************************************
    Copyright (C) Martin Karsten 2015-2019

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#ifndef _BlockingSync_h_
#define _BlockingSync_h_ 1

Martin Karsten's avatar
Martin Karsten committed
20
#include "runtime/Debug.h"
Martin Karsten's avatar
Martin Karsten committed
21 22
#include "runtime/Stats.h"
#include "runtime/StackContext.h"
Martin Karsten's avatar
Martin Karsten committed
23
#include "runtime-glue/RuntimeContext.h"
Martin Karsten's avatar
Martin Karsten committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include "runtime-glue/RuntimeLock.h"
#include "runtime-glue/RuntimeTimer.h"

#include <list>
#include <map>

class BaseTimer;
class TimerQueue;

// DEADLOCK AVOIDANCE RULE: acquire Timer lock while BlockingQueue lock held, but not vice versa!

class TimerQueue {
  RuntimeLock lock;
  std::multimap<Time,BaseTimer*> queue;
  TimerStats* stats;

public:
  typedef typename std::multimap<Time,BaseTimer*>::iterator Handle;

  TimerQueue() { stats = new TimerStats(this); }

  Handle insert(BaseTimer& bt, const Time& relTimeout, const Time& absTimeout) {
    ScopedLock<RuntimeLock> al(lock);
    Handle ret = queue.insert( {absTimeout, &bt} ); // set up timeout
    if (ret == queue.begin()) Runtime::Timer::newTimeout(relTimeout);
    return ret; // returns with lock held
  }

  void erase(Handle titer) {
    ScopedLock<RuntimeLock> al(lock);
    queue.erase(titer);
  }

  inline bool checkExpiry(const Time& now, Time& newTime);
};

class BaseTimer {
  TimerQueue::Handle thandle;
protected:
  TimerQueue& tQueue;
  void prepareRelative(const Time& timeout) {
    thandle = tQueue.insert(*this, timeout, timeout + Runtime::Timer::now());
  }
  void prepareAbsolute(const Time& timeout, const Time& now) {
    thandle = tQueue.insert(*this, timeout - now, timeout);
  }
public:
  BaseTimer(TimerQueue& tq = Runtime::Timer::CurrTimerQueue()) : tQueue(tq) {}
  void cancel() { tQueue.erase(thandle); }
  virtual bool checkTimer() { return true; }
  virtual void fireTimer() = 0;
};

class BaseSuspender {
protected:
79
  void prepareSuspend() {
Martin Karsten's avatar
Martin Karsten committed
80 81 82 83 84 85 86 87 88 89 90
    RuntimeDisablePreemption();
  }
  void doSuspend(StackContext& cs) {
    cs.suspend(_friend<BaseSuspender>());
    RuntimeEnablePreemption();
  }
};

class TimeoutInfo : public virtual BaseSuspender, public BaseTimer {
public:
  StackContext& stack;
Martin Karsten's avatar
Martin Karsten committed
91
  TimeoutInfo(StackContext& stack = *Context::CurrStack()) : stack(stack) {}
Martin Karsten's avatar
Martin Karsten committed
92
  void suspendRelative(const Time& timeout) {
93
    prepareSuspend();
Martin Karsten's avatar
Martin Karsten committed
94 95 96 97
    prepareRelative(timeout);
    doSuspend(stack);
  }
  virtual void fireTimer() {
98
    DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(&stack), " timed out");
Martin Karsten's avatar
Martin Karsten committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    stack.resume();
  }
};

class ResumeInfo {
protected:
  void setupResumeRace(StackContext& cs) {
    cs.setupResumeRace(*this, _friend<ResumeInfo>());
  }
public:
  virtual void cancelTimer() {}
};

template<typename Lock>
class BlockingInfo : public virtual BaseSuspender, public ResumeInfo {
protected:
  Lock& lock;
public:
  BlockingInfo(Lock& l) : lock(l) {}
Martin Karsten's avatar
Martin Karsten committed
118
  void suspend(StackContext& stack = *Context::CurrStack()) {
119
    prepareSuspend();
Martin Karsten's avatar
Martin Karsten committed
120 121 122
    lock.release();
    doSuspend(stack);
  }
Martin Karsten's avatar
Martin Karsten committed
123
  void suspend(BlockedStackList& queue, StackContext& stack = *Context::CurrStack()) {
Martin Karsten's avatar
Martin Karsten committed
124
    setupResumeRace(stack);
125
    prepareSuspend();
Martin Karsten's avatar
Martin Karsten committed
126 127 128 129 130 131 132 133 134 135 136
    queue.push_back(stack);
    lock.release();
    doSuspend(stack);
  }
};

template<typename Lock>
class TimeoutBlockingInfo : public BlockingInfo<Lock>, public TimeoutInfo {
  using BaseBI = BlockingInfo<Lock>;
  bool timedOut;
public:
Martin Karsten's avatar
Martin Karsten committed
137
  TimeoutBlockingInfo(Lock& l, StackContext& stack = *Context::CurrStack()) : BaseBI(l), TimeoutInfo(stack), timedOut(false) {}
Martin Karsten's avatar
Martin Karsten committed
138 139
  bool suspendAbsolute(BlockedStackList& queue, const Time& timeout, const Time& now) {
    BaseBI::setupResumeRace(stack);
140
    prepareSuspend();
Martin Karsten's avatar
Martin Karsten committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    queue.push_back(stack);
    BaseTimer::prepareAbsolute(timeout, now);
    BaseBI::lock.release();
    doSuspend(stack);
    return !timedOut;
  }
  virtual bool checkTimer() {
    return stack.raceResume();
  }
  virtual void fireTimer() {
    timedOut = true;
    BaseBI::lock.acquire();
    BlockedStackList::remove(stack);
    BaseBI::lock.release();
    TimeoutInfo::fireTimer();
  }
  virtual void cancelTimer() {
    timedOut = false;
    TimeoutInfo::cancel();
  }
};

inline bool TimerQueue::checkExpiry(const Time& now, Time& newTime) {
  bool retcode = false;
  std::list<BaseTimer*> fireList; // defer event locks
  lock.acquire();
  int cnt = 0;
  for (auto it = queue.begin(); it != queue.end(); ) {
    if (it->first > now) {
      retcode = true;
      newTime = it->first - now;
  break;
    }
#if TESTING_ENABLE_STATISTICS
    cnt += 1;
#endif
    BaseTimer* timer = it->second;
    if (timer->checkTimer()) {
      it = queue.erase(it);
      fireList.push_back(timer);
    } else {
      it = next(it);
    }
  }
  stats->events.add(cnt);
  lock.release();
  for (auto f : fireList) f->fireTimer(); // timeout lock released
  return retcode;
}

static inline void sleepStack(const Time& timeout) {
  TimeoutInfo ti;
Martin Karsten's avatar
Martin Karsten committed
193
  DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(Context::CurrStack()), " sleep ", timeout);
Martin Karsten's avatar
Martin Karsten committed
194 195 196 197 198 199 200 201 202 203 204
  ti.suspendRelative(timeout);
}

class BlockingQueue {
  BlockedStackList queue;

  BlockingQueue(const BlockingQueue&) = delete;            // no copy
  BlockingQueue& operator=(const BlockingQueue&) = delete; // no assignment

public:
  BlockingQueue() = default;
Martin Karsten's avatar
Martin Karsten committed
205
  ~BlockingQueue() { RASSERT0(empty()); }
Martin Karsten's avatar
Martin Karsten committed
206 207 208 209
  bool empty() const { return queue.empty(); }

  template<typename Lock>
  void reset(Lock& lock) {
Martin Karsten's avatar
Martin Karsten committed
210
    RASSERT0(lock.test());
Martin Karsten's avatar
Martin Karsten committed
211 212 213 214 215 216 217
    StackContext* s = queue.front();
    while (s != queue.edge()) {
      ResumeInfo* ri = s->raceResume();
      StackContext* ns = BlockedStackList::next(*s);
      if (ri) {
        ri->cancelTimer();
        BlockedStackList::remove(*s);
218
        DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(s), " clear/resume from ", FmtHex(&queue));
Martin Karsten's avatar
Martin Karsten committed
219 220 221 222 223 224 225 226
        s->resume();
      }
      s = ns;
    }
    lock.release();
    while (!empty()) Pause();     // wait for timed out events to disappear
  }
  template<typename Lock>
227
  bool block(Lock& lock, bool wait = true) {
Martin Karsten's avatar
Martin Karsten committed
228 229
    if (wait) {
      BlockingInfo<Lock> bi(lock);
Martin Karsten's avatar
Martin Karsten committed
230
      DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(Context::CurrStack()), " blocking on ", FmtHex(&queue));
Martin Karsten's avatar
Martin Karsten committed
231
      bi.suspend(queue);
Martin Karsten's avatar
Martin Karsten committed
232
      DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(Context::CurrStack()), " continuing on ", FmtHex(&queue));
Martin Karsten's avatar
Martin Karsten committed
233 234 235 236 237 238 239 240 241 242 243
      return true;
    }
    lock.release();
    return false;
  }

  template<typename Lock>
  bool block(Lock& lock, const Time& timeout) {
    Time now = Runtime::Timer::now();
    if (timeout > now) {
      TimeoutBlockingInfo<Lock> tbi(lock);
Martin Karsten's avatar
Martin Karsten committed
244
      DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(Context::CurrStack()), " blocking on ", FmtHex(&queue), " timeout ", timeout);
Martin Karsten's avatar
Martin Karsten committed
245
      bool ret = tbi.suspendAbsolute(queue, timeout, now);
Martin Karsten's avatar
Martin Karsten committed
246
      DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(Context::CurrStack()), " continuing on ", FmtHex(&queue));
Martin Karsten's avatar
Martin Karsten committed
247 248 249 250 251 252 253 254 255 256 257 258 259
      return ret;
    }
    lock.release();
    return false;
  }

  template<bool Enqueue = true>
  StackContext* unblock() {       // not concurrency-safe; better hold lock
    for (StackContext* s = queue.front(); s != queue.edge(); s = BlockedStackList::next(*s)) {
      ResumeInfo* ri = s->raceResume();
      if (ri) {
        ri->cancelTimer();
        BlockedStackList::remove(*s);
260
        DBG::outl(DBG::Level::Blocking, "Stack ", FmtHex(s), " resume from ", FmtHex(&queue));
Martin Karsten's avatar
Martin Karsten committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        if (Enqueue) s->resume();
        return s;
      }
    }
    return nullptr;
  }
};

template<typename Lock, bool Binary = false, typename BQ = BlockingQueue>
class FifoSemaphore {
protected:
  Lock lock;
  ssize_t counter;
  BQ bq;

276
  template<bool Yield = false, typename... Args>
Martin Karsten's avatar
Martin Karsten committed
277 278 279 280 281
  bool internalP(const Args&... args) {
    // need baton passing: counter unchanged, if blocking fails (timeout)
    if (counter < 1) return bq.block(lock, args...);
    counter -= 1;
    lock.release();
282
    if (Yield) StackContext::yield();
Martin Karsten's avatar
Martin Karsten committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    return true;
  }

public:
  explicit FifoSemaphore(ssize_t c = 0) : counter(c) {}
  // baton passing requires serialization at destruction
  ~FifoSemaphore() { ScopedLock<Lock> sl(lock); }
  bool empty() { return bq.empty(); }
  bool open() { return counter >= 1; }
  ssize_t getValue() { return counter; }

  void reset(ssize_t c = 0) {
    lock.acquire();
    counter = c;
    bq.reset(lock);
  }

  template<typename... Args>
  bool P(const Args&... args) { lock.acquire(); return internalP(args...); }
  bool tryP() { return P(false); }

  template<typename Lock2>
  bool P_unlock(Lock2& l) {
    lock.acquire();
    l.release();
308 309 310 311 312 313
    return internalP();
  }

  bool P_yield() {
    lock.acquire();
    return internalP<true>();
Martin Karsten's avatar
Martin Karsten committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  }

  void P_fake(size_t c = 1) {
    ScopedLock<Lock> al(lock);
    if (Binary) counter = 0;
    else counter -= c;
  }

  template<bool Enqueue = true>
  StackContext* V() {
    ScopedLock<Lock> al(lock);
    StackContext* sc = bq.template unblock<Enqueue>();
    if (sc) return sc;
    if (Binary) counter = 1;
    else counter += 1;
    return nullptr;
  }
};

template<typename Lock, bool OwnerLock = false, typename BQ = BlockingQueue>
class FifoMutex {
  Lock lock;
  StackContext* owner;
  BQ bq;

protected:
  template<typename... Args>
  bool internalAcquire(const Args&... args) {
Martin Karsten's avatar
Martin Karsten committed
342
    StackContext* cs = Context::CurrStack();
Martin Karsten's avatar
Martin Karsten committed
343 344 345 346
    lock.acquire();
    if (!owner) {
      owner = cs;
    } else if (owner == cs) {
Martin Karsten's avatar
Martin Karsten committed
347
      RASSERT(OwnerLock, FmtHex(owner));
Martin Karsten's avatar
Martin Karsten committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    } else {
      return bq.block(lock, args...);
    }
    lock.release();
    return true;
  }

public:
  FifoMutex() : owner(nullptr) {}
  // baton passing requires serialization at destruction
  ~FifoMutex() { ScopedLock<Lock> sl(lock); }
  bool test() const { return owner != nullptr; }

  template<typename... Args>
  bool acquire(const Args&... args) { return internalAcquire(args...); }
  bool tryAcquire() { return acquire(false); }

  void release() {
    ScopedLock<Lock> al(lock);
Martin Karsten's avatar
Martin Karsten committed
367
    RASSERT(owner == Context::CurrStack(), FmtHex(owner));
Martin Karsten's avatar
Martin Karsten committed
368 369 370 371 372 373 374 375 376 377 378 379 380
    owner = bq.unblock();
  }
};

template<typename Lock, bool OwnerLock = false, typename BQ = BlockingQueue>
class BargingMutex {
  Lock lock;
  StackContext* owner;
  BQ bq;

protected:
  template<typename... Args>
  bool internalAcquire(const Args&... args) {
Martin Karsten's avatar
Martin Karsten committed
381
    StackContext* cs = Context::CurrStack();
Martin Karsten's avatar
Martin Karsten committed
382 383 384
    for (;;) {
      lock.acquire();
      if (!owner) break;
Martin Karsten's avatar
Martin Karsten committed
385
      if (owner == cs) { RASSERT(OwnerLock, FmtHex(owner)); break; }
Martin Karsten's avatar
Martin Karsten committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
      if (!bq.block(lock, args...)) return false;
    }
    owner = cs;
    lock.release();
    return true;
  }

public:
  BargingMutex() : owner(nullptr) {}
  bool test() const { return owner != nullptr; }

  template<typename... Args>
  bool acquire(const Args&... args) { return internalAcquire(args...); }
  bool tryAcquire() { return acquire(false); }

  void release() {
    ScopedLock<Lock> al(lock);
Martin Karsten's avatar
Martin Karsten committed
403
    RASSERT(owner == Context::CurrStack(), FmtHex(owner));
Martin Karsten's avatar
Martin Karsten committed
404 405 406 407 408 409 410 411 412 413 414 415 416
    owner = nullptr;
    bq.unblock();
  }
};

template<typename Semaphore, bool OwnerLock, size_t SpinStart, size_t SpinEnd, size_t SpinCount>
class SpinMutex {
  StackContext* owner;
  Semaphore sem;

protected:
  template<typename... Args>
  bool internalAcquire(const Args&... args) {
Martin Karsten's avatar
Martin Karsten committed
417
    StackContext* cs = Context::CurrStack();
Martin Karsten's avatar
Martin Karsten committed
418
    if (OwnerLock && cs == owner) return true;
Martin Karsten's avatar
Martin Karsten committed
419
    RASSERT(cs != owner, FmtHex(cs), FmtHex(owner));
Martin Karsten's avatar
Martin Karsten committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    size_t cnt = 0;
    size_t spin = SpinStart;
    for (;;) {
      StackContext* exp = nullptr;
      if (__atomic_compare_exchange_n(&owner, &exp, cs, false, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) return true;
      if (cnt < SpinCount) {
        for (size_t i = 0; i < spin; i += 1) Pause();
        if (spin <= SpinEnd) spin += spin;
        else cnt += 1;
      } else {
        if (!sem.P(args...)) return false;
        cnt = 0;
        spin = SpinStart;
      }
    }
  }

public:
  SpinMutex() : owner(nullptr), sem(1) {}
  bool test() const { return owner != nullptr; }

  template<typename... Args>
  bool acquire(const Args&... args) { return internalAcquire(args...); }
  bool tryAcquire() { return acquire(false); }

  void release() {
Martin Karsten's avatar
Martin Karsten committed
446
    RASSERT(owner == Context::CurrStack(), FmtHex(owner));
Martin Karsten's avatar
Martin Karsten committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    __atomic_store_n(&owner, nullptr, __ATOMIC_RELAXED); // memory sync via sem.V()
    sem.V();
  }
};

template<typename BaseMutex>
class OwnerMutex : private BaseMutex {
  size_t counter;

public:
  OwnerMutex() : counter(0) {}

  template<typename... Args>
  size_t acquire(const Args&... args) {
    if (BaseMutex::internalAcquire(args...)) return ++counter; else return 0;
  }
  size_t tryAcquire() { return acquire(false); }

  size_t release() {
    if (--counter > 0) return counter;
    BaseMutex::release();
    return 0;
  }
};

template<typename Lock>
#if TESTING_MUTEX_FIFO
class Mutex : public FifoMutex<Lock> {};
#elif TESTING_MUTEX_BARGING
class Mutex : public BargingMutex<Lock> {};
#elif TESTING_MUTEX_SPIN
class Mutex : public SpinMutex<FifoSemaphore<Lock, true>, false, 4, 1024, 16> {};
#else
class Mutex : public SpinMutex<FifoSemaphore<Lock, true>, false, 0, 0, 0> {};
#endif

// simple blocking RW lock: release alternates; new readers block when writer waits -> no starvation
template<typename Lock, typename BQ = BlockingQueue>
class LockRW {
  Lock lock;
  ssize_t state;                    // -1 writer, 0 open, >0 readers
  BQ bqR;
  BQ bqW;

  template<typename... Args>
  bool internalAR(const Args&... args) {
    lock.acquire();
    if (state < 0 || !bqW.empty()) {
      if (!bqR.block(lock, args...)) return false;
      lock.acquire();
      bqR.unblock();                // waiting readers can barge after writer
    }
    state += 1;
    lock.release();
    return true;
  }

  template<typename... Args>
  bool internalAW(const Args&... args) {
    lock.acquire();
    if (state != 0) {
      if (!bqW.block(lock, args...)) return false;
      lock.acquire();
    }
    state -= 1;
    lock.release();
    return true;
  }

public:
  LockRW() : state(0) {}

  template<typename... Args>
  bool acquireRead(const Args&... args) { return internalAR(args...); }
  bool tryAcquireRead() { return acquireRead(false); }

  template<typename... Args>
  bool acquireWrite(const Args&... args) { return internalAW(args...); }
  bool tryAcquireWrite() { return acquireWrite(false); }

  void release() {
    ScopedLock<Lock> al(lock);
Martin Karsten's avatar
Martin Karsten committed
529
    RASSERT0(state != 0);
Martin Karsten's avatar
Martin Karsten committed
530 531 532 533 534
    if (state > 0) {             // reader leaves; if open -> writer next
      state -= 1;
      if (state > 0) return;
      if (!bqW.unblock()) bqR.unblock();
    } else {                     // writer leaves -> readers next
Martin Karsten's avatar
Martin Karsten committed
535
      RASSERT0(state == -1);
Martin Karsten's avatar
Martin Karsten committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549
      state += 1;
      if (!bqR.unblock()) bqW.unblock();
    }
  }
};

// simple blocking barrier
template<typename Lock, typename BQ = BlockingQueue>
class Barrier {
  Lock lock;
  size_t target;
  size_t counter;
  BQ bq;
public:
Martin Karsten's avatar
Martin Karsten committed
550
  Barrier(size_t t = 1) : target(t), counter(0) { RASSERT0(t); }
Martin Karsten's avatar
Martin Karsten committed
551
  void reset(size_t t = 1) {
Martin Karsten's avatar
Martin Karsten committed
552
    RASSERT0(t);
Martin Karsten's avatar
Martin Karsten committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566
    lock.acquire();
    target = t;
    counter = 0;
    bq.reset(lock);
  }
  bool wait() {
    lock.acquire();
    counter += 1;
    if (counter == target) {
      while (bq.unblock());
      counter = 0;
      lock.release();
      return true;
    } else {
567
      bq.block(lock);
Martin Karsten's avatar
Martin Karsten committed
568 569 570 571 572 573 574 575 576 577 578 579
      return false;
    }
  }
};

// simple blocking condition variable: assume caller holds lock
template<typename Lock, typename BQ = BlockingQueue>
class Condition {
  BQ bq;
public:
  bool empty() { return bq.empty(); }
  void reset(Lock& lock) { bq.reset(lock); }
580
  bool wait(Lock& lock) { return bq.block(lock); }
Martin Karsten's avatar
Martin Karsten committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
  bool wait(Lock& lock, const Time& timeout) { return bq.block(lock, timeout); }
  template<bool Broadcast = false>
  void signal() { while (bq.unblock() && Broadcast); }
};

// cf. condition variable: assume caller to wait/post holds lock
template<typename Lock>
class SynchronizedFlag {

public:
  enum State { Running = 0, Dummy = 1, Posted = 2, Detached = 4 };

protected:
  union {                             // 'waiter' set <-> 'state == Waiting'
    StackContext* waiter;
    State         state;
  };

public:
  static const State Invalid = Dummy; // dummy bit never set (for ManagedArray)
  SynchronizedFlag(State s = Running) : state(s) {}
  void reset()          { state = Running; }
  bool posted()   const { return state == Posted; }
  bool detached() const { return state == Detached; }

  bool wait(Lock& lock) {             // returns false, if detached
    if (state == Running) {
      BlockingInfo<Lock> bi(lock);
Martin Karsten's avatar
Martin Karsten committed
609
      waiter = Context::CurrStack();
Martin Karsten's avatar
Martin Karsten committed
610 611 612 613 614
      bi.suspend(*waiter);
      lock.acquire();                 // reacquire lock to check state
    }
    if (state == Posted) return true;
    if (state == Detached) return false;
Martin Karsten's avatar
Martin Karsten committed
615
    RABORT(FmtHex(state));
Martin Karsten's avatar
Martin Karsten committed
616 617 618
  }

  bool post() {                       // returns false, if already detached
Martin Karsten's avatar
Martin Karsten committed
619
    RASSERT0(state != Posted);       // check for spurious posts
Martin Karsten's avatar
Martin Karsten committed
620 621 622 623 624 625 626
    if (state == Detached) return false;
    if (state != Running) waiter->resume();
    state = Posted;
    return true;
  }

  void detach() {                     // returns false, if already posted or detached
Martin Karsten's avatar
Martin Karsten committed
627
    RASSERT0(state != Detached && state != Posted);
Martin Karsten's avatar
Martin Karsten committed
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    if (state != Running) waiter->resume();
    state = Detached;
  }
};

// cf. condition variable: assume caller to wait/post holds lock
template<typename Runner, typename Result, typename Lock>
class Joinable : public SynchronizedFlag<Lock> {
  using Baseclass = SynchronizedFlag<Lock>;
protected:
  union {
    Runner* runner;
    Result  result;
  };

public:
  Joinable(Runner* t) : runner(t) {}

  bool wait(Lock& bl, Result& r) {
    bool retcode = Baseclass::wait(bl);
    r = retcode ? result : 0; // result is available after returning from wait
    return retcode;
  }

  bool post(Result r) {
    bool retcode = Baseclass::post();
    if (retcode) result = r;  // still holding lock while setting result
    return retcode;
  }

  Runner* getRunner() const { return runner; }
};

template<typename Lock>
class SyncPoint : public SynchronizedFlag<Lock> {
  using Baseclass = SynchronizedFlag<Lock>;
  typedef typename Baseclass::State State;
  Lock lock;
public:
  SyncPoint(State s = Baseclass::Running) : Baseclass(s) {}
  void reset()  { ScopedLock<Lock> al(lock); Baseclass::reset(); }
  bool wait()   { ScopedLock<Lock> al(lock); return Baseclass::wait(lock); }
  bool post()   { ScopedLock<Lock> al(lock); return Baseclass::post(); }
  void detach() { ScopedLock<Lock> al(lock); Baseclass::detach(); }
};

#endif /* _BlockingSync_h_ */