Search code examples
c++mutexpoco

Poco ScopedLock in a loop


Say I have something like this:

#include <iostream>
#include <Poco/Mutex.h>

Poco::FastMutex mutex;

int main()
{
    for(int i = 0; i < 10; ++i)
    {
        Poco::FastMutex::ScopedLock lock(mutex);

        // do some stuff...
    }

    return 0;
};

Will the mutex be acquired on every iteration or only once? If I want to protect the whole loop, would it be better to move it outside, like this?

{
    Poco::FastMutex::ScopedLock lock(mutex);

    for(int i = 0; i < 10; ++i)
    {

        // do some stuff...
    }

    return 0;
}

Solution

  • The mutex will be acquired at each iteration.
    So yes, you have to move the lock outside the loop to protect the whole loop.