Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lock_guard in loop

Tags:

c++

stl

mutex

I have an array where each of its entries is a linked list. To avoid synchronization problems when accessing the linked lists I added a mutex to each entry.

My question is can I convert the following calls to lock and unlock in each iteration of the loop to one lock_guard as shown below? Will the mutex of each entry be unlocked after each iteration? Thanks.

for(int i = 0; i < TABLE_SIZE; ++i)
{
    table[i].entryMtx.lock ();

    //... access the linked list of the entry...

    table[i].entryMtx.unlock ();
}

// --->

for(int i = 0; i < TABLE_SIZE; ++i)
{
    std::lock_guard < std::mutex > lk (table[i].entryMtx);

    // ... access the linked list of the entry
}
like image 202
Revital Eres Avatar asked Mar 16 '17 02:03

Revital Eres


1 Answers

Yes, this is how destructors are used in C++ (and other languages).

However, it's not stdx, it's std. Probably a typo.

like image 183
Tatsuyuki Ishi Avatar answered Oct 27 '22 23:10

Tatsuyuki Ishi