Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>On the first question, how to compute the ranges to compute for each thread: I extracted constants and gave them names, in order to make the code easier to read. For good practices I also used a <a href="https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11">lambda</a> which makes the code easier to modify - code in the lambda will only ever be used here, while the function <code>f</code> can be used from other code throughout the program. Make use of this to put shared parts of the code in a function and specialized that are only ever used once in the lambda.</p> <pre><code>const size_t itemsPerThread = std::max(1, n/threads); for (size_t nextIndex= 0; nextIndex&lt; v.size(); nextIndex+= itemsPerThread) { const size_t beginIndex = nextIndex; const size_t endIndex =std::min(nextIndex+itemsPerThread, v.size()) std::cout &lt;&lt; beginIndex &lt;&lt; " " &lt;&lt; endIndex &lt;&lt; std::endl; t.push_back(std::thread([&amp;v,beginIndex ,endItem]{f(v,beginIndex,endIndex);}); } </code></pre> <p>An advanced use case would make use of a thread pool, but how this will look depends on your application design and is not covered by the STL. For a good example of a threading model see the <a href="http://doc.qt.digia.com/qt/thread-basics.html" rel="nofollow noreferrer">Qt Framework</a>. If you're just getting started with threads save this for later.</p> <p>The second question was already answered in the comments. The <code>std::thread::join</code> function will wait(block) until the thread has finished. By calling the join function on each thread and reaching the code after the join function, you can be sure that all there threads have finished and can now be deleted.</p>
    singulars
    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.
 

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