title: Thread synchronization in client-server like application?
body: <p>I have been working on a file download application, where server continiously waits new connection requests from clients, when a new connection arrives server accepts this connection and creates a new process to serve the client recently connected to server. Clients can request to download multiple files from server. For each file , client and server sides create a new thread and the data transfer for each file should be carried out between the proper thread couples of the server and client. I'm using C and <strong>pthread</strong> for threads. I have stable socket connection and successful process creation for each client for now. </p>
  
  <p>For threaded file transer, i had an attempt as follows:</p>
  
  <p>In client i'm creating threads which runs a method to receive files: </p>
  
  <pre><code>        int k;
          for (k = 0; k &lt; fNameCounter; k++)
          {
              pthread_t thread_id;
              int status = pthread_create(&amp;thread_id, NULL, &amp;receiveFile, fName );
  
              if (status != 0)
              {
                  printf("Thread Creation Failed \n");
                  exit(0);
              }
          }
  </code></pre>
  
  <p>Similarly in server side, i create same number of threads as follows:</p>
  
  <pre><code>        int k;
          for (k = 0; k &lt; fnameCounter; k++)
          {
              pthread_t thread_id;
              int status = pthread_create(&amp;thread_id, NULL, &amp;sendFile, fName );
  
              if (status != 0)
              {
                  printf("Thread Creation Failed \n");
                  exit(0);
              }
          }
  </code></pre>
  
  <p>sendFile and receiveFile functions simply writes and reads the bytes of files specified by fName(as you can see in pthread_create) by socket, at that point i have a major problem:</p>
  
  <p>In this program as far as i  thought, there might be problems that files' contents may be different after the all threads complete receiving data from server, because since sendFile and readFile functions just reads from the socket and writes to the socket. </p>
  
  <p>How can i guarantee that, each thread of client gets the proper data from the proper thread of server like i explained below:</p>
  
  <pre><code>        receive         send
  
  cthread1 ----&gt;  a.txt  &lt;-----   sthread1
  
  cthread1 ----&gt;  a.txt  &lt;-----   sthread1
  
  cthread1 ----&gt;  a.txt  &lt;-----   sthread1
  </code></pre>
  
  <p>p.s.  i'm aware that creating many threads on one socket does not makes sense but, it is my hw and i need to do in that way :/.</p>
  
  <p>Regards.</p>