Avatar ·

std::unique_lock vs std::lock_guard: what to choose for a mutex in C++?

Hello! I started learning multithreading in C++11 and got confused about choosing between std::unique_lock and std::lock_guard. Both classes are used for locking a mutex, but I don't understand in which cases to use which.\n\nFor example, I'm writing a simple thread-safe counter:\n\n```cpp\n#include \n#include \n#include \n\nstd::mutex mtx;\nint counter = 0;\n\nvoid increment() {\n for (int i = 0; i < 100000; ++i) {\n // What is better here?\n std::lock_guard lock(mtx);\n // or\n std::unique_lock lock(mtx);\n ++counter;\n }\n}\n```\n\nBoth options compile and work. But I heard that unique_lock is "heavier". When should it be used? Are there situations where lock_guard is not suitable? And why in