IanCZane IanCZane - 1 month ago 11
C++ Question

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

Here's a quick outline of my class:

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


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

I've tried it this way within
sortData
:

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

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
{
public:
    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)
            thread.join();

    }

private:
    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.

Comments