mutex.h 13.9 KB
Newer Older
1
/*
2
 * Copyright (c) 2014-2015, Siemens AG. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef EMBB_BASE_MUTEX_H_
#define EMBB_BASE_MUTEX_H_

#include <embb/base/internal/platform.h>
#include <embb/base/exceptions.h>
32
#include <embb/base/c/mutex.h>
33 34 35 36

namespace embb {
namespace base {
/**
37 38 39 40 41 42 43 44 45 46
 * \defgroup CPP_CONCEPTS_MUTEX Mutex Concept
 *
 * \brief Concept for thread synchronization.
 *
 * \anchor CPP_CONCEPTS_MUTEX_ANCHOR
 *
 * \ingroup CPP_CONCEPT
 * \{
 * \par Description
 *
Tobias Schuele committed
47 48 49 50
 12345678901234567890123456789012345678901234567890123456789012345678901234567890
 * The mutex concept is used for thread synchronization and provides a lock.
 * At any point in time, only one thread can exclusively hold the lock and
 * the lock is held until the thread explicitly releases it.
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 79 80 81 82 83 84 85 86 87 88 89 90
 *
 * \par Requirements
 * - Let \c Mutex be the mutex type
 * - Let \c m be an object of type \c Mutex.
 *
 * \par Valid Expressions
 *
 * <table>
 *   <tr>
 *     <th>Expression</th>
 *     <th>Return type</th>
 *     <th>Description</th>
 *   </tr>
 *   <tr>
 *     <td>Mutex()</td>
 *     <td>\c void</td>
 *     <td>Constructs a mutex.</td>
 *   </tr>
 *   <tr>
 *     <td>m.TryLock()</td>
 *     <td>\c bool</td>
 *     <td>Tries to lock the mutex and immediately returns. Returns \c false, if
 *     the mutex could not be acquired (locked), otherwise \c true.
 *   </tr>
 *   <tr>
 *     <td>m.Lock()</td>
 *     <td>\c void</td>
 *     <td>Locks the mutex. When the mutex is already locked, the current thread
 *     is blocked until the mutex is unlocked.</td>
 *   </tr>
 *   <tr>
 *     <td>m.Unlock()</td>
 *     <td>\c void</td>
 *     <td>Unlocks the mutex.</td>
 *   </tr>
 * </table>
 * \}
 */

/**
91 92 93 94 95 96 97 98
 * \defgroup CPP_BASE_MUTEX Mutex and Lock
 *
 * Mutexes and locks for thread synchronization.
 *
 * \ingroup CPP_BASE
 */

/**
99
 * Forward declaration for friending.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 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
 */
class ConditionVariable;

namespace internal {
/**
 * Provides main functionality for mutexes.
 */
class MutexBase {
 public:
  /**
   * Creates internal representation.
   *
   * \notthreadsafe
   */
  explicit MutexBase(
    int mutex_type
    /**< [IN] Mutex type as used in embb_mutex_init(). */
    );

  /**
   * Destroys internal representation.
   */
  virtual ~MutexBase() = 0;

  /**
   * Waits until the mutex can be locked and locks it.
   *
   * \pre The mutex is not locked by the current thread or is of type
   *      RecursiveMutex.
   * \post The mutex is locked
   * \threadsafe
   * \see TryLock(), Unlock()
   */
  void Lock();

  /**
   * Tries to lock the mutex and returns immediately.
   *
   * \post If successful, the mutex is locked
   * \return \c true if mutex could be locked, otherwise \c false
   * \threadsafe
   * \see Lock(), Unlock()
   */
  bool TryLock();

  /**
   * Unlocks a locked mutex.
   *
   * \pre The mutex is locked by the current thread
   * \post The mutex is unlocked if the number of unlock operations has reached
   *       the number of lock operations
   * \threadsafe
   * \see Lock(), TryLock()
   */
  void Unlock();

 private:
  /**
   * Holds the actual mutex.
   */
  internal::MutexType mutex_;

  /**
   * For access to native implementation type.
   */
  friend class embb::base::ConditionVariable;
};
} // namespace internal

/**
170 171
 * Spinlock
 *
172 173 174
 * \concept{CPP_CONCEPTS_MUTEX}
 *
 * \ingroup CPP_BASE_MUTEX
175 176 177 178 179 180 181 182
 */
class Spinlock {
 public:
  /**
   * Creates a spinlock which is in unlocked state.
   *
   * \notthreadsafe
   */
Christian Kern committed
183
  Spinlock();
184 185 186 187 188 189

  /**
   * Destructs a spinlock.
   *
   * \notthreadsafe
   */
Christian Kern committed
190
  ~Spinlock();
191 192 193 194 195

  /**
   * Waits until the spinlock can be locked and locks it.
   *
   * \pre The spinlock is not locked by the current thread.
Tobias Schuele committed
196
   * \post The spinlock is locked.
197 198 199
   * \threadsafe
   * \see TryLock(), Unlock()
   */
Christian Kern committed
200
  void Lock();
201 202 203 204 205 206 207 208 209 210

  /**
   * Tries to lock the spinlock for \c number_spins times and returns.
   *
   * \pre The spinlock is not locked by the current thread.
   * \post If successful, the spinlock is locked.
   * \return \c true if the spinlock could be locked, otherwise \c false.
   * \threadsafe
   * \see Lock(), Unlock()
   */
211 212
  bool TryLock(
    unsigned int number_spins = 1
Tobias Schuele committed
213
    /**< [IN] Maximal number of spins when trying to acquire the lock.
Christian Kern committed
214
     * Note that passing 0 here results in not trying to obtain the lock at all.
Tobias Schuele committed
215
     * The default parameter is 1.
Christian Kern committed
216 217
     */
    );
218 219 220 221

  /**
   * Unlocks the spinlock.
   *
Tobias Schuele committed
222 223
   * \pre The spinlock is locked by the current thread.
   * \post The spinlock is unlocked.
224 225 226
   * \threadsafe
   * \see Lock(), TryLock()
   */
Christian Kern committed
227
  void Unlock();
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

 private:
  /**
   * Disables copy construction and assignment.
   */
  Spinlock(const Spinlock&);
  Spinlock& operator=(const Spinlock&);

  /**
   * Internal spinlock from base_c
   */
  embb_spinlock_t spinlock_;
};

/**
243 244 245 246 247 248 249 250
 * Non-recursive, exclusive mutex.
 *
 * Mutexes of this type cannot be locked recursively, that is, multiple times
 * by the same thread with unlocking it in between. Moreover, it cannot be
 * copied or assigned.
 *
 * \see RecursiveMutex
 * \ingroup CPP_BASE_MUTEX
251 252
 *
 * \concept{CPP_CONCEPTS_MUTEX}
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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 308 309 310 311 312 313 314 315 316 317 318 319 320 321
 */
class Mutex : public internal::MutexBase {
 public:
  /**
   * Creates a mutex which is in unlocked state.
   *
   * \memory Potentially allocates dynamic memory
   * \notthreadsafe
   */
  Mutex();

#ifdef DOXYGEN

  /**
   * Waits until the mutex can be locked and locks it.
   *
   * \pre The mutex is not locked by the current thread.
   * \post The mutex is locked
   * \threadsafe
   * \see TryLock(), Unlock()
   */
  void Lock();

  /**
   * Tries to lock the mutex and returns immediately.
   *
   * \pre The mutex is not locked by the current thread.
   * \post If successful, the mutex is locked.
   * \return \c true if the mutex could be locked, otherwise \c false.
   * \threadsafe
   * \see Lock(), Unlock()
   */
  bool TryLock();

  /**
   * Unlocks the mutex.
   *
   * \pre The mutex is locked by the current thread
   * \post The mutex is unlocked
   * \threadsafe
   * \see Lock(), TryLock()
   */
  void Unlock();

#endif // DOXYGEN

 private:
  /**
   * Disables copy construction and assignment.
   */
  Mutex(const Mutex&);
  Mutex& operator=(const Mutex&);

  /**
   * For access to native implementation type.
   */
  friend class ConditionVariable;
};

/**
 * Recursive, exclusive mutex.
 *
 * Mutexes of this type can be locked recursively, that is, multiple times by
 * the same thread without unlocking it in between. It is unlocked only, if the
 * number of unlock operations has reached the number of previous lock
 * operations by the same thread. It cannot be copied or assigned.
 *
 * \see Mutex
 * \ingroup CPP_BASE_MUTEX
322 323
 *
 * \concept{CPP_CONCEPTS_MUTEX}
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
 */
class RecursiveMutex : public internal::MutexBase {
 public:
  /**
   * Creates a mutex which is in unlocked state.
   *
   * \memory Potentially allocates dynamic memory
   * \notthreadsafe
   */
  RecursiveMutex();

#ifdef DOXYGEN

  /**
   * Waits until the mutex can be locked and locks it.
   *
   * \post The mutex is locked
   * \threadsafe
   * \see TryLock(), Unlock()
   */
  void Lock();

  /**
   * Tries to lock the mutex and returns immediately.
   *
   * \post If successful, the given mutex is locked.
   * \return \c true if the mutex could be locked, otherwise \c false.
   * \threadsafe
   * \see Lock(), Unlock()
   */
  bool TryLock();

  /**
   * Unlocks a locked mutex.
   *
   * \pre The mutex is locked by the current thread.
   * \post The mutex is unlocked if the number of unlock operations has reached
   *       the number of lock operations.
   * \threadsafe
   * \see Lock(), TryLock()
   */
  void Unlock();

#endif // DOXYGEN

 private:
  /**
   * Disables copy construction and assignment.
   */
  RecursiveMutex(const RecursiveMutex&);
  RecursiveMutex& operator=(const RecursiveMutex&);
};

/**
 * Scoped lock (according to the RAII principle) using a mutex.
 *
 * The mutex is locked on construction and unlocked on leaving the scope of the
 * lock.
 *
383 384 385 386
 * \tparam Mutex Used mutex type. Has to fulfil the
 *         \ref CPP_CONCEPTS_MUTEX_ANCHOR "Mutex Concept".
 *
 * \see UniqueLock
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 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 446 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
 * \ingroup CPP_BASE_MUTEX
 */
template<typename Mutex = embb::base::Mutex>
class LockGuard {
 public:
  /**
   * Creates the lock and locks the mutex.
   *
   * \pre The given mutex is unlocked
   * \notthreadsafe
   */
  explicit LockGuard(
    Mutex& mutex
    /**< [IN] Mutex to be guarded */
    ) : mutex_(mutex) {
    mutex_.Lock();
  }

  /**
   * Unlocks the mutex.
   */
  ~LockGuard() {
    mutex_.Unlock();
  }

 private:
  /**
   * Holds reference to mutex realizing the lock.
   */
  Mutex& mutex_;

  /**
   * Disable copy construction and assignment.
   */
  LockGuard(const LockGuard<Mutex>&);
  LockGuard<Mutex>& operator=(const LockGuard<Mutex>&);
};

/**
 * \name UniqueLock Tag Variables
 * \{
 */

/**
 * Tag type for deferred UniqueLock construction.
 *
 * Use the defer_lock variable in constructor calls.
 */
struct DeferLockTag {};

/**
 * Tag variable for deferred UniqueLock construction.
 *
 * \ingroup CPP_BASE_MUTEX
 */
const DeferLockTag defer_lock = DeferLockTag();

/**
 * Tag type for try-lock UniqueLock construction.
 *
 * Use the try_lock variable in constructor calls.
 */
struct TryLockTag {};

/**
 * Tag variable for try-lock UniqueLock construction.
 *
 * \ingroup CPP_BASE_MUTEX
 */
const TryLockTag try_lock = TryLockTag();

/**
 * Tag type for adopt UniqueLock constructor.
 *
 * Use the adopt_lock variable in constructor calls.
 */
struct AdoptLockTag {};

/**
 * Tag variable for adopt UniqueLock construction.
 *
 * \ingroup CPP_BASE_MUTEX
 */
const AdoptLockTag adopt_lock = AdoptLockTag();

/** \} */

/**
 * Flexible ownership wrapper for a mutex.
 *
 * Provides exception controlled locking of a mutex with non-recursive semantics,
 * that gives more flexibility than LockGuard but also has slightly increased
 * memory and processing overhead. Each instance of a UniqueLock can be used by
 * one thread only!
 *
 * \notthreadsafe
 * \see Mutex, LockGuard
484 485
 * \tparam Mutex Used mutex type. Has to fulfil the
 *         \ref CPP_CONCEPTS_MUTEX_ANCHOR "Mutex Concept".
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 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
 * \ingroup CPP_BASE_MUTEX
 */
template<typename Mutex = embb::base::Mutex>
class UniqueLock {
 public:
  /**
   * Creates a lock without assigned mutex.
   *
   * A mutex can be assigned to the lock using the method Swap().
   */
  UniqueLock();

  /**
   * Creates a lock from an unlocked mutex and locks it.
   *
   * \pre \c mutex is unlocked
   */
  explicit UniqueLock(
    Mutex& mutex
    /**< [IN] Mutex to be managed. */
    );

  /**
   * Creates a lock from an unlocked mutex without locking it.
   *
   * \pre \c mutex is unlocked
   */
  UniqueLock(
    Mutex& mutex,
    /**< [IN] Mutex to be managed */
    DeferLockTag
    /**< [IN] Tag to select correct constructor */
    );

  /**
   * Creates a lock from an unlocked mutex and tries to lock it.
   *
   * \pre \c mutex is unlocked
   */
  UniqueLock(
    Mutex& mutex,
    /**< [IN] Mutex to be managed */
    TryLockTag
    /**< [IN] Tag to select correct constructor */
    );

  /**
   * Creates a lock from an already locked mutex.
   *
   * \pre \c mutex is locked
   */
  UniqueLock(
    Mutex& mutex,
    /**< [IN] Mutex to be managed */
    AdoptLockTag
    /**< [IN] Tag to select correct constructor */
    );

  /**
   * Unlocks the mutex if owned.
   */
  ~UniqueLock();

  /**
   * Waits until the mutex is unlocked and locks it.
   *
   * \throws ErrorException, if no mutex is set or it is locked
   */
  void Lock();

  /**
   * Tries to lock the mutex and returns immediately.
   *
   * \return \c true if the mutex could be locked, otherwise \c false.
   * \throws ErrorException, if no mutex is set
   */
  bool TryLock();

  /**
   * Unlocks the mutex.
   *
   * \throws ErrorException, if no mutex is set or it is not locked
   */
  void Unlock();

  /**
572
   * Exchanges ownership of the wrapped mutex with another lock.
573 574 575
   */
  void Swap(
    UniqueLock<Mutex>& other
576
    /**< [IN/OUT] The lock to exchange ownership with */
577 578 579 580 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 609 610 611 612 613 614 615 616 617 618 619 620
    );

  /**
   * Gives up ownership of the mutex and returns a pointer to it.
   *
   * \return A pointer to the owned mutex or NULL, if no mutex was owned
   */
  Mutex* Release();

  /**
   * Checks whether the mutex is owned and locked.
   *
   * \return \c true if mutex is locked, otherwise \c false.
   */
  bool OwnsLock() const;

 private:
  /**
   * Holds reference to mutex realizing the lock.
   */
  Mutex* mutex_;

  /**
   * Stores information about whether the unique lock has locked the mutex.
   */
  bool locked_;

  /**
   * Disable copy construction and assignment.
   */
  UniqueLock(const UniqueLock<Mutex>&);
  UniqueLock<Mutex>& operator=(const UniqueLock<Mutex>&);

  /**
   * For access to native implementation type.
   */
  friend class embb::base::ConditionVariable;
};
} // namespace base
} // namespace embb

#include <embb/base/internal/mutex-inl.h>

#endif // EMBB_BASE_MUTEX_H_