Skip to main content

Concurrency

  • Chapter
  • First Online:
C++ Standard Library Quick Reference
  • 3276 Accesses

Abstract

To run any function pointer, functor, or lambda expression in a new thread of execution, pass it to the constructor of std::thread, along with any number of arguments. For example, these two lines are equivalent.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

eBook
USD 19.99
Price excludes VAT (USA)
  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Notes

  1. 1.

    Scheduled to be added by the C++17 version of the Standard Library.

  2. 2.

    Although normally uncommon, try_lock() is allowed to spuriously fail: that is, return false even though the mutex is not owned by any other thread. Take that into account when designing more advanced synchronization scenarios.

  3. 3.

    With condition_variable, this exact lock and mutex type must be used. To use other standard types, or any object with public lock() and unlock() functions, the more general std::condition_variable_any class is declared, which is otherwise analogous to condition_variable.

  4. 4.

    Some care must be taken: it introduces a window for race conditions between setting the condition and the notification of waiting threads. In certain cases, notifying while holding the lock may actually lead to more predictable results and avoid subtle races. When in doubt, it is best to not unlock the mutex when notifying, because the performance impact is likely to be minimal.

  5. 5.

    A trivially copyable type has no nontrivial copy/move constructor/assignment, no virtual functions or bases, and a trivial destructor. Essentially, these are the types that can safely be bit-wise copied (for example, using memcpy()).

Author information

Authors and Affiliations

Authors

Rights and permissions

Reprints and permissions

Copyright information

© 2016 Peter Van Weert and Marc Gregoire

About this chapter

Cite this chapter

Van Weert, P., Gregoire, M. (2016). Concurrency. In: C++ Standard Library Quick Reference. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-1876-1_7

Download citation

Publish with us

Policies and ethics