lundi 29 janvier 2018

std::lock_guard constructor instantiation order

I suppose this is more a general question about lvalue instantiation ordering.

In short, is this safe?:

void func1()
{
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

void func2()
{
    func1();
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

I am somewhat concerned that the compiler may call the constructor of the lock_guard before calling func1 from within func2, thus causing a deadlock.

Is it guaranteed that this is safe or do I need to do something like this:

void func1()
{
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

void func2()
{
    func1();

    { //lock
        std::lock_guard< std::mutex > lock( mutex );
        //do some stuff in locked context
    } //unlock
}

Aucun commentaire:

Enregistrer un commentaire