Note that there are some explanatory texts on larger screens.

plurals
  1. POParallelize a loop using std::thread and good practices
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/10792157/c-2011-stdthread-simple-example-to-parallelize-a-loop">C++ 2011 : std::thread : simple example to parallelize a loop?</a> </p> </blockquote> <p>Consider the following program that distribute a computation over the elements of a vector (I never used std::thread before):</p> <pre><code>// vectorop.cpp // compilation: g++ -O3 -std=c++0x vectorop.cpp -o vectorop -lpthread // execution: time ./vectorop 100 50000000 // (100: number of threads, 50000000: vector size) #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;thread&gt; #include &lt;cmath&gt; #include &lt;algorithm&gt; #include &lt;numeric&gt; // Some calculation that takes some time template&lt;typename T&gt; void f(std::vector&lt;T&gt;&amp; v, unsigned int first, unsigned int last) { for (unsigned int i = first; i &lt; last; ++i) { v[i] = std::sin(v[i])+std::exp(std::cos(v[i]))/std::exp(std::sin(v[i])); } } // Main int main(int argc, char* argv[]) { // Variables const int nthreads = (argc &gt; 1) ? std::atol(argv[1]) : (1); const int n = (argc &gt; 2) ? std::atol(argv[2]) : (100000000); double x = 0; std::vector&lt;std::thread&gt; t; std::vector&lt;double&gt; v(n); // Initialization std::iota(v.begin(), v.end(), 0); // Start threads for (unsigned int i = 0; i &lt; n; i += std::max(1, n/nthreads)) { // question 1: // how to compute the first/last indexes attributed to each thread // with a more "elegant" formula ? std::cout&lt;&lt;i&lt;&lt;" "&lt;&lt;std::min(i+std::max(1, n/nthreads), v.size())&lt;&lt;std::endl; t.push_back(std::thread(f&lt;double&gt;, std::ref(v), i, std::min(i+std::max(1, n/nthreads), v.size()))); } // Finish threads for (unsigned int i = 0; i &lt; t.size(); ++i) { t[i].join(); } // question 2: // how to be sure that all threads are finished here ? // how to "wait" for the end of all threads ? // Finalization for (unsigned int i = 0; i &lt; n; ++i) { x += v[i]; } std::cout&lt;&lt;std::setprecision(15)&lt;&lt;x&lt;&lt;std::endl; return 0; } </code></pre> <p>There is already two questions embedded in the code. </p> <p>A third one would be: is this code is completely ok or could it be written in a more elegant way using std::threads ? I do not know the "good practices" using std::thread...</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