Skip to Content
C++ High Performance
book

C++ High Performance

by Viktor Sehr, Björn Andrist
January 2018
Intermediate to advanced
374 pages
9h 53m
English
Packt Publishing
Content preview from C++ High Performance

Avoiding deadlocks

As long as a thread never acquires more than one lock at a time, there is no risk of deadlocks. Sometimes, though, it is necessary to acquire another lock while already holding on to a previously acquired lock. The risk of deadlocks in those situations can be avoided by grabbing both locks at the exact same time. C++ has a way to do this by using the std::lock() function, which takes an arbitrary number of locks, and blocks until all locks have been acquired.

The following is an example of transferring money between accounts. Both accounts need to be protected during the transaction, and therefore we need to acquire two locks at the same time. Here is how it works:

struct Account { Account() {} int balance_ = 0; std::mutex ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance - Second Edition

C++ High Performance - Second Edition

Björn Andrist, Viktor Sehr
Advanced C++

Advanced C++

Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
C++ In a Nutshell

C++ In a Nutshell

Ray Lischner
C++ Cookbook

C++ Cookbook

D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell

Publisher Resources

ISBN: 9781787120952Supplemental Content