Skip to content

enh(ScopedLock): ScopedLock add std::adopt_lock, try_to_lock, defer_lock#5005

Merged
matejk merged 1 commit intopocoproject:mainfrom
siren186:enh/try_to_lock
Sep 11, 2025
Merged

enh(ScopedLock): ScopedLock add std::adopt_lock, try_to_lock, defer_lock#5005
matejk merged 1 commit intopocoproject:mainfrom
siren186:enh/try_to_lock

Conversation

@siren186
Copy link
Copy Markdown
Member

STL has 3 lock type:

Type Effect(s)
std::try_to_lock_t try to acquire ownership of the mutex without blocking
std::adopt_lock_t assume the calling thread already has ownership of the mutex
std::defer_lock_t do not acquire ownership of the mutex

STL demo

void demo1() {
	std::mutex m;
	std::unique_lock<std::mutex> lk(m, std::try_to_lock); // call try_lock()
	if (lk.owns_lock()) {
    	std::cout << "Locked";
	}  
}

void demo2() {
	std::mutex m;
    m.lock(); // already locked
    std::unique_lock<std::mutex> lk(m, std::adopt_lock); // will auto unlock in destructor
}

void demo3() {
    std::mutex m1, m2;
    
    // do not lock in constructor, and it will auto unlock in destructor if it is locked
    std::unique_lock<std::mutex> lk1(m1, std::defer_lock);
    std::unique_lock<std::mutex> lk2(m2, std::defer_lock);
    
    std::lock(lk1, lk2);
}

Poco demo

void demo1() {
    Poco::Mutex m;
    Poco::Mutex::ScopedLockWithUnlock lk(m, std::try_to_lock); // call tryLock()
    if (lk.ownsLock()) {
    	std::cout << "Locked";
    }    
}

void demo2() {
    Poco::Mutex m;
    m.lock(); // already locked
    Poco::Mutex::ScopedLockWithUnlock lk(m, std::adopt_lock); // will auto unlock in destructor
}

void demo3() {
    Poco::Mutex m1, m2;

    // do not lock in constructor, and it will auto unlock in destructor if it is locked
    Poco::Mutex::ScopedLockWithUnlock lk1(m1, std::defer_lock);
    Poco::Mutex::ScopedLockWithUnlock lk2(m2, std::defer_lock);
    
    // Poco has no function like `std::lock(lk1, lk2)`
    lk1.lock();
    lk2.lock();
}

@matejk matejk added this to the Release 1.15.0 milestone Sep 5, 2025
@matejk matejk merged commit 85d9643 into pocoproject:main Sep 11, 2025
36 checks passed
@siren186 siren186 deleted the enh/try_to_lock branch September 12, 2025 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants