Skip to Content
Advanced C++ Programming Cookbook
book

Advanced C++ Programming Cookbook

by Dr. Rian Quinn
January 2020
Intermediate to advanced
454 pages
11h 25m
English
Packt Publishing
Content preview from Advanced C++ Programming Cookbook

std::timed_mutex

Finally, we have not dealt with the scenario where a thread that acquired a mutex crashed. In this scenario, any thread that attempts to acquire the same mutex would enter a deadlock state as the thread that crashed never gets a chance to call unlock(). One way to prevent this issue is to use std::timed_mutex.

For example, consider the following code:

#include <mutex>#include <thread>#include <iostream>std::timed_mutex m{};void foo(){    using namespace std::chrono;    if (m.try_lock_for(seconds(1))) {        std::cout << "lock acquired\n";    }    else {        std::cout << "lock failed\n";    }}int main(void){    std::thread t1{foo};    std::thread t2{foo};    t1.join();    t2.join();    return 0;}

When this is executed, we get the following:

In the preceding example, ...

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

Modern C++ Programming Cookbook

Modern C++ Programming Cookbook

Marius Bancila

Publisher Resources

ISBN: 9781838559915Supplemental Content