mercredi 27 janvier 2016

Cant call pass in a parameter to a function of a thread unless it is a pointer. How to pass in just a value?

void static_thread_function(std::string param, int id)
{
    y.lock();
    std::cout<< id << std::endl;
    std::cout<< param << std::endl;
    y.unlock();
}        

Result dispatchThreads(Lines const& lines, int numThreads)
        {

        std::vector<std::thread> threadArray;
        std::vector<Result> results;
        for (int i = 0; i<numThreads; i++)
        {
            results.push_back({0,0,0});
        }
           for(int i = 0; i < numThreads; i++)
            {
            std::string l = lines[i];
            threadArray.push_back(std::thread(static_thread_function, l, i));
        }
        for (auto &var: threadArray)
            var.join();
    }

I am trying to pass a string into a thread's function. The strings are kept in a vector. It is making me pass a pointer to the string because "Expression must be rvalue". The problem is that what the pointer points to changes every time the for loop loops so each thread only works on the last bit of the string. TL;DR I would like to be able to use the value of a string as a parameter to the function called by a thread but it will only let me use a pointer to the string. I have tried using std::move() and passing in a substring but I can't seem to get it to work. According to what I have researched

threadArray.push_back(std::thread(static_thread_function, l, i));

should work but it doesn't. Help please?

Aucun commentaire:

Enregistrer un commentaire