educative.io

Why do we unlock then lock the thread in the while loop?

        while (size == 0) {
            lock.unlock();
            lock.lock();
        }

Why not just

        while (size == 0) {
            lock.lock();
        }

is it because we can’t re-lock a mutex? Or is it because the application may ignore this as the stat is basically the same?

Unlocking the lock gives other threads a chance to acquire the lock and do something actually useful.

For example - if we never released the lock, the size can never change from 0 (since other producers/consumers can’t get the lock) and we would deadlock here.