0

I have an object like this:

class Blocking_queue
{
private:
    queue<T> my_queue;
    unsigned int dim;
    mutex  m;
    condition_variable cv;
}

In my main I want to create some threads which call the object methods:

Blocking_queue<int> q(6);
    thread t(close, q);

How can I do my copy constructor with the mutex? I think that I cannot simply do like this because it's not copiable

Blocking_queue(const Blocking_queue& source){
        this->queue = source.queue;
        this->dim = source.dim;
        this->m = source.m;
        this->cv = source.cv;

    }
Seba92
  • 446
  • 1
  • 4
  • 17
  • What behavior do you want? Do you want to call `close` on a thread with *this* `q` or with a *different* `q`? – Barry May 19 '15 at 10:33
  • 1
    You've found out that the class will be non-copyable. Great. Now you need to tell us what semantics you _do_ want. What are you asking for, really? Why do you need a copy constructor? That all being said, if you _do_ want the class to be copyable, it _may_ be acceptable to create a new mutex in each copy. It just depends mate. – Lightness Races in Orbit May 19 '15 at 10:34
  • Ok sorry I didn't explain well. I just want to call from main a method on this q. I thought that I need a copy constructor for doing thread t(close, q); – Seba92 May 19 '15 at 10:43
  • If you'd copy it, it would not be the same queue. Which is almost certainly *not* what you want? – stijn May 19 '15 at 10:49
  • yes correct, as petersohn said I just had to pass by reference but I didn't know the sintax ref(), so the copy constructor is useless in my case – Seba92 May 19 '15 at 10:52
  • Definite duplicate of that question then. – Barry May 19 '15 at 10:54

1 Answers1

1

If you really want to copy the contents of the queue and have two separate, independent queues, you should copy the contents and initialize new mutexes, like this:

Blocking_queue(const Blocking_queue& source){
    this->queue = source.queue;
    this->dim = source.dim;
}

Or better yet, like this:

Blocking_queue(const Blocking_queue& source):
    queue(source.queue),
    dim(source.dim) {
}

But it's probably not what you want. If you want this object to be shared between threads, pass it by reference:

Blocking_queue<int> q(6);
thread t(close, ref(q));

Or, if the thread may last longer than the scope of the function where you defined the queue, use shared pointers to make sure the object remains valid.

auto q = make_shared<Blocking_queue<int>>(6);
thread t(close, q));
petersohn
  • 11,292
  • 13
  • 61
  • 98