0% found this document useful (0 votes)
49 views5 pages

C++ Mutex Class Exercises

The document discusses exercises using C++ std::mutex class including: describing std::mutex, rewriting a program to protect output operations using a mutex, writing a program with two threads where one locks a mutex and sleeps while the other tries locking with try_lock() and sleeps if unsuccessful, and observing the behavior with try_lock().

Uploaded by

mohamed attia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views5 pages

C++ Mutex Class Exercises

The document discusses exercises using C++ std::mutex class including: describing std::mutex, rewriting a program to protect output operations using a mutex, writing a program with two threads where one locks a mutex and sleeps while the other tries locking with try_lock() and sleeps if unsuccessful, and observing the behavior with try_lock().

Uploaded by

mohamed attia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mutex Class Exercises

Copyright © James Raynard 2023


std::mutex Class
• Briefly describe the C++ std::mutex

Copyright © James Raynard 2023


Rewrite using std::mutex
• Rewrite the "scrambled output" program using a mutex to protect the
output operations
• Verify that the output is not scrambled when there are ten
concurrent threads running

Copyright © James Raynard 2023


try_lock()
• Write a program which runs two task functions in separate threads
• The first task function locks a mutex, sleeps for 500ms and releases
the lock
• The second task function sleeps for 100ms, then calls try_lock() to
lock the mutex. If unsuccessful, it sleeps again for 100ms and calls
try_lock() again. If successful, it unlocks the mutex
• Add suitable print statements and run the program

Copyright © James Raynard 2023


try_lock()
• What do you observe?

Copyright © James Raynard 2023

You might also like