#include#include #include std::mutex mtx; void increment(int &count) { for(int i = 0; i < 100; i++) { mtx.lock(); count++; mtx.unlock(); } } int main() { int count = 0; std::thread t1(increment, std::ref(count)); std::thread t2(increment, std::ref(count)); t1.join(); t2.join(); std::cout << "Final count: " << count << std::endl; return 0; }
#includeThis example shows how a custom Mutex class (`MyMutex`) can be created using atomic operations. The `print` function is called by two separate threads, and each thread prints a message to the console inside a Mutex lock. The custom Mutex class `MyMutex` uses `atomic#include #include #include class MyMutex { public: void lock() { while(flag.exchange(true)); } void unlock() { flag.store(false); } private: std::atomic flag{false}; }; MyMutex mtx; void print(const char *str, int num) { for(int i = 0; i < 5; i++) { mtx.lock(); std::cout << str << num << std::endl; mtx.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } int main() { std::thread t1(print, "Thread ", 1); std::thread t2(print, "Thread ", 2); t1.join(); t2.join(); return 0; }