Threads by C++11

I made thread array in 20 threads and need to perform function hundred times, how can I do that to use C++11? When I used like on an example, it execute twenty times and stoped...
1
2
3
4
5
6
7
8
9
std::thread Cannibal[20];
for(int i=0;i<100;i++)
   {
      Cannibal[i] = std::thread(Dinner);
   }
for(int i=0;i<N;i++)
   {
      Cannibal[i].join();
   }
There is no need for 20 threads. The common PC only has 4. Even gaming machines usually only have 8.

Look into thread pools.
Avilius, are you talking about CPU cores? You can have more threads than cores you know...
Last edited on
Just make each thread execute the function 4 times:
1
2
3
4
5
6
7
8
9
std::thread Cannibal[20];

for (int i = 0; i < 20; ++i) {
    Cannibal[i] = std::thread([](){ Dinner(); Dinner(); Dinner(); Dinner(); });
}

for (int i = 0; i < 20; ++i) {
    Cannibal[i].join();
}


Also, @Avilius, there is nothing particularly wrong with having 20 threads. While I was writing this, my Windows machine is running 872 threads. However, there is no real need to have 20 threads if each thread does the same thing. Also, as an example, some Intel CPU's are 'hyperthreaded' - i.e. each CPU core has 2 threads.

EDIT:
@OP: The reason it didn't work is because you were accessing out of bounds memory - you were trying to access, for example, the 21st element of a 20-element array, which would often cause your program to raise a segmentation fault and crash.
Last edited on
And what if I have next writing to call the Class method by thread from another class:
Cannibals[i] = std::thread(&Cannibals::Dinner, &c);
where c the object of the Class "Cannibals" and how can I add dynamic to call, if I must will be change 20 to 80 and 100 to 320?

And how can I correct my fault if I need to take access 20 threads and count 100 elements, where I must to count 1 elements per thread?

Last edited on
Satansoft wrote:
And what if I have next writing to call the Class method by thread from another class:
Cannibals[i] = std::thread(&Cannibals::Dinner, &c);

Pass the element of the class, and execute the function using that object:
Cannibals[i] = std::thread([&](){ c.Dinner(); c.Dinner(); c.Dinner(); c.Dinner(); c.Dinner(); });

Satansoft wrote:
how can I add dynamic to call, if I must will be change 20 to 80 and 100 to 320?

I don't know what you mean here... could you explain this better?

Satansoft wrote:
And how can I correct my fault if I need to take access 20 threads and count 100 elements, where I must to count 1 elements per thread?

Assuming you mean how can you have 20 threads be 100 threads (which is what it looks like you are asking) - you can't. That makes no sense - you have to have each thread doing 1 call.

Also, in my earlier post I made a silly mistake - it should execute each function 5 times (100 / 20 = 5, not 4).
Last edited on
Topic archived. No new replies allowed.