IanCZane IanCZane - 1 year ago 73
C++ Question

Trying to start threads of a member function from within a class

Here's a quick outline of my class:

class foo{
vector<string> rawData;
vector<vector<string> > slicedData;
void readData();
void sortData();
static void selectionSort(vector<string>);

with information from an external file. Once it does this,
splits that data into subsets, each of which is stored in
. I need to spawn a thread of
to sort each subset, and I have to do so inside of

I've tried it this way within

thread *threads = new thread[slicedData.size()];

for(int i = 0; i < slicedData.size(); i++){
threads[i] = thread(selectionSort,slicedData[i]);

...but when I do so, g++ throws
error: attempt to use a deleted function

For the record, I need to store the threads in an array so I can join them later. I realize this could be done more elegantly with the boost library and thread groups, but I'm trying to keep this project dependency-free.

Answer Source

I couldn't reproduce your error, but the following code compiles for me.

I would recommend using a vector of threads and calling emplace_back() to create the threads inside the vector..

Something like this:

class foo
    std::vector<std::vector<std::string> > slicedData;

    void sortData()
        std::vector<std::thread> threads;

        // for each slice add a new thread passing the function and data
        // to its constructor
        for(auto& slice: slicedData)
            threads.emplace_back(&foo::selectionSort, std::ref(slice));
            // NOTE: use of std::ref() to pass by reference

        // now join the threads to prevent the threads vector
        // going out of scope before they finish
        for(auto&& thread: threads)


    static void selectionSort(std::vector<std::string>&); // pass by reference

Also note I pass the data by reference because I suspect you don't really want to sort a copy of the data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download