title: Sharing a list between threads in C++
body: <p>I am having a problem with sharing a list between 2 or more threads at C++. I initialize my list in main() and then create the threads, passing the list object pointer as argument: </p>
  
  <pre><code>pthread_create(&amp;(tid[i]), NULL, &amp;threadfunction, &amp;l);
  </code></pre>
  
  <p>where <code>&amp;l</code> is the argument. Is this the correct way to manipulate the same list from 2 or more threads? I use a simple mutex for locking/unlocking, so no more than one thread is accessing it at a time.</p>
  
  <p>EDIT: code below</p>
  
  <hr>
  
  <pre><code>#include &lt;stdio.h&gt; 
  #include &lt;string.h&gt; 
  #include &lt;pthread.h&gt; 
  #include &lt;stdlib.h&gt; 
  #include &lt;unistd.h&gt;
  #include "list.h" 
  
  using namespace std;
  int count = 0;
  pthread_t tid[2]; 
  pthread_mutex_t lock; 
  
  void* trythis(void *arg) 
  { 
      pthread_mutex_lock(&amp;lock); 
      printf("Starting thread\n");
      count++;
      printf("%d\n", count);
      if(count == 1)
      {
          ((list *)arg)-&gt;Append((char *)"some", (char *)"thing");
          printf("Appending done\n");
      }
      else
      {
          ((list *)arg)-&gt;Append((char *)"some", (char *)"else");
          printf("Appending done\n");
      }
  
      pthread_mutex_unlock(&amp;lock); 
  
      return NULL; 
  } 
  
  int main(void) 
  { 
      list* l = new list();
      int i = 0; 
      printf("Starting\n");
      if (pthread_mutex_init(&amp;lock, NULL) != 0) 
      { 
          printf("mutex init has failed\n"); 
          return 1; 
      } 
  
  while(i &lt; 2) 
  { 
      int err = pthread_create(&amp;(tid[i]), NULL, &amp;trythis, &amp;l); 
      if (err != 0) 
          printf("\nThread can't be created :[%s]", strerror(err)); 
      i++; 
  } 
  
  pthread_join(tid[0], NULL); 
  printf("Im out 1\n");
  pthread_join(tid[1], NULL); 
  printf("Im out 2\n");
  
  pthread_mutex_destroy(&amp;lock); 
  
  delete l;
  return 0; 
  </code></pre>
  
  <p>} </p>
  
  <hr>
  
  <p>The Append() function is just adding some elements in the list ( every list Node has 2 char* members).</p>