2

Edit/Solved: Joachim Pileborg's answer did the job for me. THX

Please be gentle as this is my first question.

I am actual lerning and playing with c++ in particular threading. I looked for an answer (and it would astonish me if there is not allready one out there, but i wasn't able to find it).

So back to topic: My "play" code looks something like this (Console application)

void foo(){
//do something
}

int _tmain(int argc, _TCHAR* argv[])
{
std::thread t[threadcount];
        for (int i = 0; i < threadcount; ++i) {
            t[i] = std::thread(foo);
        }
        for (int i = 0; i < threadcount; ++i) {
            t[i].join();
        }
}

Is it possible to set the value of threadcount through argv? If not could someone please give me a short snippet on how to implement

std::thread::hardware_concurrency()

as the threadcount, because also there Visualstudio gives me an error when setting

const int threadcount = std::thread::hardware_concurrency();

Thanks in advance.

1 Answers1

2

As the number of threas is to be controlled by threadcount, setting it from the command line can be implemented by adding

int threadcount = atoi(argv[1]);

to the implementation. Some error checking could be done, e.g. reporting an error on a non-positive number of threads.

If the number of threads is to be determined programmatically, depending on the specific platform, this question could be interesting.

Community
  • 1
  • 1
Codor
  • 17,447
  • 9
  • 29
  • 56
  • Yes that was basicly one of my ideas, but when doing this, Visualstudio gives me: C2057: expected constant expression – Oniuoniu Onuoinuo Jan 28 '16 at 07:56
  • If I'm not mistaken, the error seems unrelated; have you tried omitting `const` from the declaration of `threadcount`? – Codor Jan 28 '16 at 07:58
  • 2
    @OniuoniuOnuoinuo C++ doesn't have [*variable-length arrays*](http://en.wikipedia.org/wiki/Variable-length_array) so you can't create an array using a variable as size. Use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) instead. – Some programmer dude Jan 28 '16 at 07:59