Search code examples
c++multithreadingboostc++11boost-thread

How do I stop std/boost::thread copying my object rather than passing references?


From the output of this sample project I am seeing three copies of my object created when I'd expect only one. And want only one. How should I fix this?

In my real code ThreadedThing is a significantly larger/heavier class that sits in a threadpool and I'd rather have only as many of them as I really need. But I've written a little demo app (below) that demonstrates the behaviour. I copied the basic code from a boost threading sample so I expected it to work properly, so I fear this is a C++ novice question.

I've written multithreaded code before, but in Delphi rather than C++. For this code valgrind says there's no leaks, which is all very well but there are still three objects created where I would rather have one.

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

class ThreadedThing {
public:
    ThreadedThing() {
        cout << "ThreadedThing created" << endl;
    }
    ThreadedThing(const ThreadedThing &orig) {
        cout << "ThreadedThing copy created" << endl;
    }
    ~ThreadedThing() {
        cout << "ThreadedThing destroyed" << endl;
    }
    void operator()() {
        cout << "ThreadedThing running" << endl;
        sleep(2);
    }
};

int main() {
    std::vector < shared_ptr < boost::thread >> threads;
    cout << "Started" << endl;

    ThreadedThing thing;
    std::shared_ptr<boost::thread> thread(new boost::thread(thing));
    threads.push_back(thread);

    for (std::vector < std::shared_ptr < boost::thread >> ::iterator it = threads.begin(); it != threads.end(); ++it) {
        (*it)->join();
        cout << "joined" << endl;
    }
    cout << "stopped" << endl;
    return 0;
}

/* output
Started
ThreadedThing created
ThreadedThing copy created
ThreadedThing copy created
ThreadedThing destroyed
ThreadedThing running
ThreadedThing destroyed
joined
stopped
ThreadedThing destroyed
*/

Solution

  • Simply use std::ref in C++11 or boost::ref when not having access to C++11.