Skip to content

Instantly share code, notes, and snippets.

@arcticmatt
Created January 9, 2020 05:41
Show Gist options
  • Save arcticmatt/6e451ef2bff5177a6606ffe752c4fc05 to your computer and use it in GitHub Desktop.
Save arcticmatt/6e451ef2bff5177a6606ffe752c4fc05 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <mutex>
std::mutex globalMutex;
class CustomScopedLock {
public:
CustomScopedLock(std::mutex &m) : m_(m) {
std::cout << "CustomScopedLock locking mutex..." << std::endl;
m_.lock();
std::cout << "CustomScopedLock has locked mutex!" << std::endl;
};
~CustomScopedLock() {
m_.unlock();
std::cout << "CustomScopedLock has unlocked mutex" << std::endl;
};
private:
std::mutex &m_;
};
void lockMutexBad(bool shouldThrow) {
std::cout << "Locking mutex manually..." << std::endl;
globalMutex.lock();
std::cout << "Mutex is locked!" << std::endl;
// Could also imagine this as an early return. If you use a plain old
// mutex, you have to remember to manually unlock before every return...
// and it's quite easy to forget.
if (shouldThrow) {
std::cout << "Throwing exception" << std::endl;
throw 1;
}
globalMutex.unlock();
std::cout << "Mutex has been unlocked manually" << std::endl;
}
void lockMutexBadExample() {
try {
lockMutexBad(true);
} catch (...) {
std::cout << "Caught exception" << std::endl;
}
lockMutexBad(false);
}
void lockMutexGood(bool shouldThrow) {
std::cout << "Locking mutex with scoped_lock..." << std::endl;
std::scoped_lock lock(globalMutex);
std::cout << "Mutex is locked!" << std::endl;
if (shouldThrow) {
std::cout << "Throwing exception" << std::endl;
throw 1;
}
}
void lockMutexGoodExample() {
try {
lockMutexGood(true);
} catch (...) {
std::cout << "Caught exception" << std::endl;
}
lockMutexGood(false);
}
void lockMutexCustomScopeLock(bool shouldThrow) {
CustomScopedLock lock(globalMutex);
if (shouldThrow) {
std::cout << "Throwing exception" << std::endl;
throw 1;
}
}
void lockMutexCustomScopeLock() {
try {
lockMutexCustomScopeLock(true);
} catch (...) {
std::cout << "Caught exception" << std::endl;
}
lockMutexCustomScopeLock(false);
}
int main() {
lockMutexBadExample();
// lockMutexGoodExample();
// lockMutexCustomScopeLock();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment