首页 > 解决方案 > 创建线程时如何运行线程主方法?

问题描述

我的线程的主要方法是:

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]);
   }
}

我每次使用另一种方法创建一个线程列表:

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;
}

我遇到的主要问题std::ref(interFac[thr])是使我的#include <thread>文件无法正常工作。我曾尝试通过引用取消通行证,但这无济于事。

标签: c++multithreadingoperating-system

解决方案


我不知道这interFac是为了什么,但它看起来像这样:

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

应该是这样的:

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

然后它编译


推荐阅读