Note that there are some explanatory texts on larger screens.

plurals
  1. POposting future and new threads in a loop multiple times
    primarykey
    data
    text
    <p>I am writing a program that does calculations in multiple threads and return the result using c++ future, here's a simplified version of my code</p> <pre><code>int main() { int length = 64; vector&lt;std::future&lt;float&gt;&gt; threads(length); vector&lt;float&gt; results(length); int blockLength = 8; int blockCount = length/blockLength; for(int j=0;j&lt;blockCount;j++) { for(int i=0;i&lt;blockLength;i++) { threads[i + j * blockLength] = std::async(func1,i*j); } for(int i=0;i&lt;blockLength;i++) { results[i + j * blockLength] = threads[i].get(); } } </code></pre> <p>the definition of func1 is simplified as follows:</p> <pre><code>float func1(int input) { //calculations... return result; } </code></pre> <p>I would like that the program above does 64 times of calculations, in 8 threads at a time, so that the processor and memory usage would be better at the same time.</p> <p>The program is conceived that it will post <code>blockLength</code> number of threads at a time, and wait till the calculation results are obtained, and proceed to the next loop.</p> <p>the program will post <code>blockLength</code> number of threads for <code>blockCount</code> times, for example, 8 threads for 8 times.</p> <p>but the program is not working, there is always a <code>EXC_BAD_ACCESS</code> exception when the first loop of <code>blockLength</code> threads finishes, besides, the calculation time of each thread is not guaranteed, any thread can run for a long time or finish quickly.</p> <p>Here is a screenshot: <img src="https://i.stack.imgur.com/5iyz0.png" alt="exception at the beginning of a new loop"></p> <p>as is shown above, the CPU usage drops as some of the threads finish, but an exception is thrown as soon as the second loop starts.</p> <p>Would you please point out what is wrong with my usage of <code>future</code>? How can we correct it?</p> <p>Thank you very much!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload