title: Using pthread_mutex_t in cpp
body: <p>In my program I have a daemon thread that waits for tasks and print them to a file.
  Its function is:</p>
  
  <pre><code>void * deamon(void *) {
      while(true) {
          pthread_mutex_lock(manager-&gt;getLock());
          while(!manager-&gt;isPending()) {
              if (manager-&gt;isClosing()) {
                  pthread_exit(NULL);
              }
              pthread_cond_wait(manager-&gt;getCond(), manager-&gt;getLock());
              //check that condition if met - surprises may occur!
          }
                  //WRITE TO FILE HERE
          pthread_mutex_unlock(manager-&gt;getLock());
      }
      return NULL;
  }
  </code></pre>
  
  <p>So as you can see the when there are no pending task the daemon waits for new ones.
  When I get a new one I push it to a data base in a different class (daemon is not in a class) and then send a signal as follows:</p>
  
  <pre><code>void Manager::pushNewTask(Task * task) {
      pthread_mutex_lock(_lock);
      map&lt;int,Task *&gt;::iterator it = _tasks-&gt;end();
      _tasks-&gt;insert(it,make_pair(task-&gt;getId(),task));
      // At the first time a signal is sent with no need
      if (_tasks-&gt;size() == 1) {
          _pending = true;
          pthread_cond_signal(_cond); //SEND SIGNAL TO DAEMON THREAD
      }
      pthread_mutex_unlock(_lock);
  }
  </code></pre>
  
  <p>Three questions:</p>
  
  <ol>
  <li>Its not clear from the code here but both <code>daemon()</code> and <code>pushNewTask()</code> use the same <code>pthread_mutex_t</code> object - is that not a problem? When daemon goes to sleep (wait) it doesn't unlock the mutex.</li>
  <li>What is the meaning that several functions are locked with the same <code>pthread_mutex_lock</code>? Maybe that only one thread can access either of them? When should I use different <code>pthread_mutex_t objects</code>?</li>
  </ol>
  
  <p>Thanks</p>