title: Multithreaded MD5 Hashing
body: <p>i'm trying to multithread a program wich take word from file then hash these and write to another.</p>
  
  <p>If i make it without multithreading it's really fast, it's able to use only 15-20% of the CPU and has out like 300.000line/s</p>
  
  <p>But when i tryied with multithreading it only slow down and start to hash only at 17000lines/s, can you please help me?</p>
  
  <p>Thanks</p>
  
  <pre><code>#include &lt;iostream&gt;     // std::cout, std::streambuf, std::streamsize
  #include &lt;fstream&gt;      // std::ifstream
  #include &lt;string&gt;
  #include &lt;thread&gt;
  #include "md5.h"
  
  using namespace std;
  
  static const int num_threads = 10;
  
  void call_from_thread(int tid) {
      cout &lt;&lt; "Launched by thread " &lt;&lt; tid &lt;&lt; std::endl;
      int cl = 0;
      int uscita = 0;
      int parole = 0;
      char* contents;
      ifstream istr("test.txt");
  
      if (istr) {
          streambuf * pbuf = istr.rdbuf();
          streamsize size = pbuf-&gt;pubseekoff(0, istr.end);
          pbuf-&gt;pubseekoff(0, istr.beg);       // rewind
          contents = new char[size];
          pbuf-&gt;sgetn(contents, size);
          istr.close();
  
          ofstream myfile;
          myfile.open("out.txt");
  
          do {
              string prova("");
              uscita = 0;
              do {
                  if (contents[cl] == '\n') {
                      uscita = 1;
                  }
                  prova += contents[cl];
                  cl += 1;
              } while (uscita != 1);
              parole += 1;
              //cout &lt;&lt; prova &lt;&lt; ":" &lt;&lt; md5(prova) &lt;&lt; endl;
              myfile &lt;&lt; prova &lt;&lt; ":" &lt;&lt; md5(prova) &lt;&lt; endl;
          } while (parole != 9586054);
  
          myfile.close();
      }
  }
  
  int main()
  {
  
      thread t[num_threads];
  
      //Launch a group of threads
      for (int i = 0; i &lt; num_threads; ++i) {
          t[i] = thread(call_from_thread, i);
      }
  
      cout &lt;&lt; "Launched from the main\n";
  
      //Join the threads with the main thread
      for (int i = 0; i &lt; num_threads; ++i) {
          t[i].join();
      }
  
      return 0;
  }
  </code></pre>