Writing a thread-safe class
When dealing with multiple threads, writing a thread-safe class becomes an absolute must. If we do not write classes that are thread safe, there are many complications that may arise, such as deadlocks. We must also keep in mind that when we write a thread-safe class, there is no potential danger from data races and mutex.
Getting ready
For this recipe, you will need a Windows machine and an installed version Visual Studio.
How to do it…
In this recipe, we will see how easy it is to write a thread safe class in C++. Add a source file called Source.cpp
and add the following code to it:
#include <thread> #include <string> #include <mutex> #include <iostream> #include <fstream> using namespace std; class DebugLogger { std::mutex MU; ofstream f; public: DebugLogger() { f.open("log.txt"); } void ResourceSharingFunction(string id, int value) { std::lock_guard<std::mutex> guard(MU); //RAII f << "From" ...