简体   繁体   中英

When creating a thread how do I run the threads main method?

The main method of my thread is:

void thrMain(const std::vector<long>& list, std::vector<int>& result,
    const int startInd, const int endInd) {
   for (int i = startInd; (i < endInd); i++) {
       result[i] = countFactors(list[i]);
   }
}

I create a list of threads each time using another method:

std::vector<int> getFactorCount(const std::vector<long>& numList, const int thrCount) {
   // First allocate the return vector
   const int listSize = numList.size();
   const int count = (listSize / thrCount) + 1;
   std::vector<std::thread> thrList;  // List of threads
   const std::vector<long> interFac(thrCount);  // Intermediate factors
   // Store factorial counts
   std::vector<int> factCounts(numList.size());
   for (int start = 0, thr = 0; (thr < thrCount); thr++, start += count) {
       int end = std::max(listSize, (start + count));
       thrList.push_back(std::thread(thrMain, std::ref(numList), 
            std::ref(interFac[thr]), start, end));
   }
   for (auto& t : thrList) {
       t.join();
   }
   // Return the result back
   return factCounts;
}

The main problem I am having is that the std::ref(interFac[thr]) is making my #include <thread> file not work. I have tried taking away the pass by reference and that does not help the problem.

I don't know what interFac is for, but it looks like this:

thrList.push_back(std::thread(thrMain, std::ref(numList), 
     std::ref(interFac[thr]), start, end));

should be this:

thrList.push_back(std::thread(thrMain, std::ref(numList), 
     std::ref(factCounts), start, end));

Then it compiles .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM