std::lock_guard calls lock at creation time and unlock at destruction time (end of block).
std::unique_lock calls lock at creation time and unlock at destruction time (end of block).
In addition, lock and unlock can be called (maintaining the state value for lock).
#include <iostream>
#include <string>
#include <mutex>
class TestMutex {
public:
void lock() {
std::cout << "call lock" << std::endl;
}
void unlock() {
std::cout << "call unlock" << std::endl;
}
};
TestMutex mutex1;
int main() {
std::cout << "###### lock_guard start" << std::endl;
{
std::lock_guard lockGuard(mutex1);
std::cout << "lock_guard created" << std::endl;
}
std::cout << "###### lock_guard end" << std::endl << std::endl;
std::cout << "###### unique_lock start" << std::endl;
{
std::unique_lock uniqueLock(mutex1);
std::cout << "unique_lock created" << std::endl;
}
std::cout << "###### unique_lock end" << std::endl << std::endl;
std::cout << "###### unique_lock start 2" << std::endl;
{
std::unique_lock uniqueLock(mutex1);
std::cout << "unique_lock created" << std::endl;
std::cout << "manual call unlock ++" << std::endl;
uniqueLock.unlock();
std::cout << "manual call unlock --" << std::endl;
}
std::cout << "###### unique_lock end 2" << std::endl << std::endl;
std::cout << "###### unique_lock start 3" << std::endl;
{
std::unique_lock uniqueLock(mutex1);
std::cout << "unique_lock created" << std::endl;
std::cout << "manual call unlock ++" << std::endl;
uniqueLock.unlock();
std::cout << "manual call unlock --" << std::endl;
std::cout << "manual call lock ++" << std::endl;
uniqueLock.lock();
std::cout << "manual call lock --" << std::endl;
}
std::cout << "###### unique_lock end 3" << std::endl << std::endl;
return 0;
}
Execution result
$ ./a.out
###### lock_guard start
call lock
lock_guard created
call unlock
###### lock_guard end
###### unique_lock start
call lock
unique_lock created
call unlock
###### unique_lock end
###### unique_lock start 2
call lock
unique_lock created
manual call unlock ++
call unlock
manual call unlock --
###### unique_lock end 2
###### unique_lock start 3
call lock
unique_lock created
manual call unlock ++
call unlock
manual call unlock --
manual call lock ++
call lock
manual call lock --
call unlock
###### unique_lock end 3
No comments:
Post a Comment