title: Multi-threaded access to a Queue in C++
body: <p>So basically I have two threads: One generates combinations of a String and appends them to a Queue that is a class member.
  The second thread is supposed to print everything that is in that queue to a file. If the queue is empty I should wait until there is another element and so forth.</p>
  
  <pre><code> std::mutex m;
  Class c{
    std::queue&lt;std::string&gt; q;
    std::ofstream file;
  
    void print(std::string str){
      file &lt;&lt; str &lt;&lt; "\n";
    } // Print to file
  
    void generate(){
      str = "abc" // do stuff
      q.push(str);
    }
  
  }
  </code></pre>
  
  <p>When I'm using <code>std::mutex</code> the program's performance gets really bad.
  I think I need a function that manages access to the queue so that i can write and print simultaneously. <strong>How do I do that?</strong></p>
  
  <pre><code>void Generator::print() {
      int c = 0;
      while (c &lt; totalN){
          if(!printQueue.empty()){
              fileStream &lt;&lt; printQueue.front() &lt;&lt; '\n';
              printQueue.pop();
              c++;
          }
      }
  }
  
  void Generator::getCombinations(unsigned long start, unsigned long end) {
  // Fill with dummy elements
  std::string comb(length, ' ');
  std::string temp(length, ' ');
  auto total_n = static_cast&lt;unsigned long&gt;(std::pow(elementCount, length));
  for (auto i = start; i &lt; end; ++i) {
      auto n = i;
      for (size_t j = 0; j &lt; length; ++j) {
          comb[comb.size() - j - 1] = charPool[n % elementCount];
          n /= elementCount;
      }
      temp = comb;
      for (auto f : tasks) (this-&gt;*f)(temp); // Call addQueue func
  }
  }
  
  
  void Generator::addToQueue(std::string &amp;str) {
      m.lock();
      printQueue.push(str);
      m.unlock();
  }
  </code></pre>
  
  <p>For some reason I get bad-access errors because the prints functions tries to print something from an empty queue which seems kind of impossible to me because this part of code is only executed if the queue is not empty...</p>