Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ OpenMP for-loop global variable problems
    primarykey
    data
    text
    <p>I'm new to OpenMP and from what I have read about OpenMP 2.0, which comes standard with Microsoft Visual Studio 2010, global variables are considered troublesome and error prone when used in parallel programming. I have also been adopting this feeling since I have found very little on how to deal with global variables and static global variables efficiently, or at all for that matter.</p> <p>I have this snippet of code which runs but because of the local variable created in the parallel block I don't get the answer I'm looking for. I get 8 different print outs (because that how many threads I have on my PC) instead of 1 answer. I know that it's because of the local variables "list" created in the parallel block but this code will not run if I move the "list" variable and make it a global variable. Actually the code does run but it never gives me an answer back. This is the sample code that I would like to modify to use a global "list" variable :</p> <pre><code>#pragma omp parallel { vector&lt;int&gt; list; #pragma omp for for(int i = 0; i &lt; 50000; i++) { list.push_back(i); } cout &lt;&lt; list.size() &lt;&lt; endl; } </code></pre> <p>Output:</p> <pre><code>6250 6250 6250 6250 6250 6250 6250 6250 </code></pre> <p>They add up to 50000 but I did not get the one answer with 50000, instead it's divided up.</p> <p>Solution:</p> <pre><code> vector&lt;int&gt; list; #pragma omp parallel { #pragma omp for for(int i = 0; i &lt; 50000; i++) { cout &lt;&lt; i &lt;&lt; endl; #pragma omp critical { list.push_back(i); } } } cout &lt;&lt; list.size() &lt;&lt; endl; </code></pre>
    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.
    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