Skip to main content

Concurrency

  • Chapter
  • First Online:
C++17 Standard Library Quick Reference
  • 2214 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 functionally equivalent:

std::thread worker1(my_callable, "arg", anotherArg); std::thread worker2([=] { my_callable("arg", anotherArg); });

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

Access this chapter

Chapter
USD 29.95
Price excludes VAT (USA)
  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
eBook
USD 34.99
Price excludes VAT (USA)
  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever
Softcover Book
USD 44.99
Price excludes VAT (USA)
  • Compact, lightweight edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Notes

  1. 1.

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

  2. 2.

    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.

  3. 3.

    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.

  4. 4.

    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 bitwise copied (e.g., using memcpy()).

Author information

Authors and Affiliations

Authors

Rights and permissions

Reprints and permissions

Copyright information

© 2019 Peter Van Weert and Marc Gregoire

About this chapter

Check for updates. Verify currency and authenticity via CrossMark

Cite this chapter

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

Download citation

Publish with us

Policies and ethics