在 C++ 中创建线程数组

Make thread array in C++

我想制作一个使用所有线程的程序。 我通过以下方式获得核心:

const auto processorCount = std::thread::hardware_concurrency();

然后我尝试这样做:


        std::thread threads[processorCount];

        for (int i = 0; i < processorCount; i++)
        {
            threads[i] = std::thread(addArray);
        }

然后它给了我这个错误。

g++ main.cpp -o build
In file included from /usr/include/c++/11/thread:43,
                 from main.cpp:1:
/usr/include/c++/11/bits/std_thread.h: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int* (&)(int*, int*); _Args = {}; <template-parameter-1-3> = void]’:
main.cpp:62:46:   required from here
/usr/include/c++/11/bits/std_thread.h:130:72: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
  130 |                                       typename decay<_Args>::type...>::value,
      |                                                                        ^~~~~
/usr/include/c++/11/bits/std_thread.h:130:72: note: ‘std::integral_constant<bool, false>::value’ evaluates to false
/usr/include/c++/11/bits/std_thread.h: In instantiation of ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >’:
/usr/include/c++/11/bits/std_thread.h:203:13:   required from ‘struct std::thread::_State_impl<std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> > >’
/usr/include/c++/11/bits/std_thread.h:143:29:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int* (&)(int*, int*); _Args = {}; <template-parameter-1-3> = void]’
main.cpp:62:46:   required from here
/usr/include/c++/11/bits/std_thread.h:252:11: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >::__result<std::tuple<int* (*)(int*, int*)> >’
  252 |           _M_invoke(_Index_tuple<_Ind...>)
      |           ^~~~~~~~~
/usr/include/c++/11/bits/std_thread.h:256:9: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >::__result<std::tuple<int* (*)(int*, int*)> >’
  256 |         operator()()
      |         ^~~~~~~~
make: *** [Makefile:2: array] Error 1

我现在该怎么办?他们这样做更简单吗?

首先,就像建议的评论一样,我建议您也使用 std::vector,例如 std::vector<std::thread>。这是它的样子的一个小例子:

#include <iostream>
#include <vector>
#include <thread>

using namespace std;

void print(int i)
{
    std::cout << i << std::endl;
}


int main()
{
    std::vector<std::thread> Threads;
    for(int i = 0; i<std::thread::hardware_concurrency(); i++)
    {
        Threads.push_back(std::thread(print, i));
    }
    for(auto& i : Threads)
    {
        i.join();
    }
    return 0;
}

希望这能解决您的问题。