Home > Blockchain >  Make thread array in C
Make thread array in C

Time:04-12

I want to make a program that makes use of all threads. I get the cores by:

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

Then I tried to do this:


        std::thread threads[processorCount];

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

Then it gave me this error.

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

What do I do now? Is their a simpler way of doing this?

CodePudding user response:

First of all, like in the comments suggested, I would recommend you to use std::vector as well, for example something like, std::vector<std::thread>. Here is a small example of how it could look like:

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

I hope this is solves your problem.

  • Related