CS360 Final -- December 11, 1999. Question 4

Here is a piece of code that serves a socket on cetus3a.cs.utk.edu, port 15000. It then allows clients to attach to it and send it 1000 bytes. These bytes are appended to the file outfile and then the number of characters written to the file so far is sent back to the client. This is a simple piece of code:
#include < stdio.h >
#include "socketfun.h"

int read1000(int fd, char *chars)
{
  int so_far, i;

  so_far = 0;
  while(so_far < 1000) {
    i = read(fd, chars+so_far, 1000-so_far);
    if (i == 0) return 0;
    so_far += i;
  }
  return 1;
}

main()
{
  int sock;
  int fd;
  char chars[1000];
  char output[20];
  FILE *fout;
  int nchars;

  sock = serve_socket("cetus3a", 15000);
  if (sock < 0) { perror("serve_socket"); exit(1); }

  fout = fopen("outfile", "w");
  if (fout == NULL) { perror("fopen(outfile)"); exit(1); }

  nchars = 0;

  while (1) {
    fd = accept_connection(sock);
    if (read1000(fd, chars) != 0) {
      fwrite(chars, 1, 1000, fout);
      nchars += 1000;
      sprintf(output, "%d\n", nchars);
      write(fd, output, strlen(output));
    }
    close(fd);
  }
}
Part 1: Turn this into threaded code, where a new thread is created to service each connection. You will need a mutex to protect the shared variables. Try to make sure that you do not lock the mutex longer than you need to. Use the skeleton in the Answer Sheet to Question 4. Don't worry about calling pthread_join(). Were we actually writing this code, we would use the jthread_create()/jthread_exit() primitives from the lecture notes on condition variables.

Part 2: Explain the conditions under which your code will be more efficient than the above code, and the conditions under which the two pieces of code perform equally.