Ken P
Ken P

Reputation: 580

Vectors of lock_guards

I'm working with some multithreaded code (working with concurrent data structures), and part of it requires that I lock a set of mutexes. For my implementation I am utilizing a vector of lock_guards, since I don't necessarily know how many mutexes I'm going to need to lock, and I may run into exception conditions which will force me to unlock all of my mutexes and restart. Hence the reason for the vector.

The code I'm trying to use boils down to this:

#include <mutex>
#include <vector>


using namespace std;

int main( int argc, char** argv ) {
    vector<recursive_mutex> vec(10);

    vector<lock_guard<recursive_mutex>> lgv;
    for( auto it = vec.begin(); it != vec.end(); ++it ) {
        lgv.emplace_back( *it );
    }

    return 0;
}

When I try to compile this (G++ 5.3.1 using --std=c++11), I get the following error (somewhat distilled):

In file included from foo.cpp:1:0:
/usr/include/c++/5.3.1/mutex:385:7: note: declared here
   lock_guard(const lock_guard&) = delete;

Based upon my understanding of emplace_back, the library should NOT be attempting to use the copy constructor for lock_guard -- it should be performing a construct-in-place. Am I understanding what SHOULD be happening properly, or is my understanding flawed?

FYI, I have attempted to use a unique_lock and this will compile just fine. However, I'm curious about this (apparent) discrepancy.

Upvotes: 2

Views: 1164

Answers (1)

SergeyA
SergeyA

Reputation: 62603

I assume, the question reflects an attemtpt to use unique_lock, which OP is saying works. The same example with lock_guard would not work, since std::vector::emplace_back requires the type to be both MoveInsertable and EmplaceConstructible, and std::lock_guard does not suit.

Upvotes: 4

Related Questions