title: Calculating prime numbers using multi threading
body: <p>I started to work with threads recently and I tried to run a simple program that uses threads but I get really strange output.
  The program writes the prime numbers in the given range with N(parameter to the function)number of threads into the file "PRIMES.txt", if the <code>range &lt;= 1000</code> the output is fine but if the range is bigger, then the output is something like :</p>
  
  <p><code>‰‱′″‵‷ㄱㄠ″㜱ㄠ‹㌲㈠‹ㄳ㌠‷ㄴ㐠″㜴㔠″㤵㘠‱㜶㜠‱㌷㜠‹㌸㠠‹㜹ㄠ㄰ㄠ㌰ㄠ㜰ㄠ㤰ㄠ㌱ㄠ㜲ㄠㄳㄠ㜳ㄠ㤳ㄠ㤴ㄠㄵㄠ㜵ㄠ㌶ㄠ㜶ㄠ㌷ㄠ㤷... (much longer)</code></p>
  
  <p>What would be the problem?</p>
  
  <p>Here is my code : </p>
  
  <p>threads.h :</p>
  
  <pre><code>#include &lt;fstream&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;thread&gt;
  using namespace std;
  
  void writePrimesToFile(int begin, int end, ofstream&amp; file);
  void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N);
  </code></pre>
  
  <p>threads.cpp :</p>
  
  <pre><code>#include "Threads.h"
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  #include &lt;thread&gt;
  #include &lt;mutex&gt;
  #include &lt;vector&gt;
  
  mutex mtx;
  
  void PrimesToFile(int begin, int end, ofstream&amp; file)
  {
  bool isPrime;
  string Primes;
  int count = 0;
  mtx.lock();
  cout &lt;&lt; "Thread is running" &lt;&lt; endl;
      for (int i = begin; i &lt; end; i++)
      {
          isPrime = true;
          for (int j = 2; j &lt; i; j++)
          {
              if (i%j == 0)
                  isPrime = false;
          }
          if (isPrime)
          {
              Primes.append(to_string(i));
              Primes.append(" ");
          }
      }
  file.write(Primes.c_str(), Primes.length());
  mtx.unlock();
  }
  
  void WritePrimesMultipleThreads(int begin, int end, string filePath, int N)
  {
      ofstream OP;
      OP.open(filePath);
      int lastPos = 0;
      int destPos = end / N;
      thread* TV = new thread[N];
      for (int i = 0; i &lt; N; i++)
      {
          TV[i] = thread(PrimesToFile, lastPos, destPos, ref(OP));
          lastPos = destPos;
          destPos += end / N;
      }
      for (int i = 0; i &lt; N; i++)
          TV[i].join();
  }
  </code></pre>
  
  <p>Starting point :</p>
  
  <pre><code>#include "Threads.h"
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  #include &lt;thread&gt;
  
  void main()
  {
      WritePrimesMultipleThreads(1, 10000, "PRIMES.txt", 5);
      system("PAUSE");
  }
  </code></pre>
  
  <p>Thanks!</p>