title: deadlock and\or return before thread is dead
body: <p>I'm stuck for about 2 days in the same situation and i'd really appreciate any help.
  The main thread is calling the <code>initDevice()</code> function, which is opening the file and creating a new thread, which he will be the "writing" thread, with the <code>writeToDeviceHandler()</code> function.
  The <code>write2device()</code> is called from main() and should insert new tasks to write (in the future) to a <code>map&lt;int,Task*&gt;</code>. The problem is, that sometimes the application is stuck at some kind of an inifinite loop or a deadlock and sometimes it writes &lt;(# of tasks) to write.
  Can anyone see if there's anything wrong in the code?
  THANKS!</p>
  
  <pre><code>int write2device(char *buffer, int length)
  {
      if(is_running)
      {
          pthread_mutex_lock(&amp;tasks_mutex);//LOCK
          int curr_id = getNextAvailableId();
          Task* new_task = new Task(buffer,length, curr_id);
          tasks[curr_id] = new_task;
          pthread_cond_signal(&amp;tasks_cv);
          given_ids.insert(curr_id);
          pthread_mutex_unlock(&amp;tasks_mutex);//UNLOCK
          return curr_id;
      }
      return FAIL;
  }
  
  int initdevice(char *filename)
  {
      is_running = true;
      pthread_cond_signal(&amp;tasks_cv);
      output_file.open(filename);
      if(!output_file.is_open())
      {
          cerr &lt;&lt; "Error opening file" &lt;&lt; endl;
          is_running = false;
          return SYSTEM_ERROR;
      }
      int res = pthread_create(&amp;writing_thread, NULL, writeToDeviceHandler, NULL);//Create the writing to file thread.
      if(res != 0)
      {
          cerr &lt;&lt;  "Error creating the writing thread" &lt;&lt;endl;
          exit(FAIL);
      }
  
      return SUCCESS;
  }
  
  void *writeToDeviceHandler(void *arg)
  {
      Task* curr_task;
      while(is_running)
      {
          pthread_mutex_lock(&amp;tasks_mutex);
          cout &lt;&lt; "IN LOOP - size of db: " &lt;&lt; tasks.size() &lt;&lt; endl;
          if(tasks.empty())
          {
              pthread_cond_wait(&amp;tasks_cv, &amp;tasks_mutex);
          }
          if(tasks.empty()) cout &lt;&lt; "Empty, still finding thread" &lt;&lt;endl;
          curr_task = tasks.begin()-&gt;second;
          if(curr_task == NULL)
          {
              pthread_mutex_unlock(&amp;tasks_mutex);
              continue;
          }
          //copy from tasks to file
          output_file.write(curr_task-&gt;getBuff(), curr_task-&gt;getLength());
  
          ids.remove(curr_task-&gt;getId());
          tasks.erase(curr_task-&gt;getId());
          delete curr_task;
          pthread_mutex_unlock(&amp;tasks_mutex);
      }
  
      pthread_exit(NULL);
      return NULL;
  }
  </code></pre>