Usenet comp.unix.osf.osf1 (1992-2004)
 help / color / mirror / Atom feed
From: Bil Lewis <Bil@LambdaCS.com>
Cc: bil@lambdacs.com
Subject: Re: pthreads and sockets
Date: 1996/12/06	[thread overview]
Message-ID: <32A8A2EA.4097@LambdaCS.com> (raw)
In-Reply-To: 589ceq$g76$1@asgard.sprintlink.co.za


Philip,

  Here's my two-bits worth.  Mind you, I am not a network dude, so my
thoughts on that part is questionable.

  First, using threads is a fine idea.  You'll like the results.  I know
that VMS implements pthreads, as does Solaris 2.5 and DEC UNIX.

  There's a nice article by Doug Schmidt & Steve Vinoski on this kind 
of programming in C++ report April '96.

  I also include some of my opinions (soon to be in a book) below.  You
can look at some comparative code which does this on my web page (below).

-Bil



philip Shearer wrote:
> 
> I am assessing the possibility of replacing a network communications
> subsystem with a TCP/IP implementation using pthreads. It is the
> first pthreaded application I have attempted , but I have a lot
> of experience of this type of application on various UNIX systems
> using sockets and fork(ing).
> 
> At the moment the sub-system runs as a server on VMS and a client
> on MS-Windows using UDP on one PORT. Built into the comms layer is
> an in-house reliable connection mechanism between the VMS server
> MS-Windows clients.
> 
> The current sub-system works for about 550 connections but it is
> starting to become flaky as more clients are added.
> 
> The development (of the server software) will be done on Solaris
> x86 V 2.5.0 and Digital UNIX 4.0.
> 
> Ideally the server code should be portable to a VMS platform.
> 
> Is is there anything that we need to do to the kernels of the
> 3 systems to allow for 1000 TCP connections?
> 
> Is there any software on the Net which does this task or
> something similar.
> 
> If not then at the moment I envisage having :
> 
>    One thread accepting connections and creating one new thread
>    per connection. (Accepter)
> 
>    One thread read-blocking on the each socket connection. Each
>    thread will write to an internal IPC that is connected to the
>    main application.(Reader)

  1000 is a lot of threads.  Probably better to do a single select()
and place the request on a queue for a producer/consumer model.
 
>    One thread will read from an internal IPC to receive processed
>    messages from the main application. (Dispatcher)
> 
>    One thread per-connection which will block waiting for the
>    Dispatcher to send it a message with it will send out onto
>    the network. (Writer)
> 
> Is there a simple method by which the Dispatcher can multiplex
> to the correct Writer (assuming that any info needed to do this
> can be prefixed to the outgoing message by the main application)
> Or will I be forced to implement some sort of structure/lookup table
> containing a mutex lock for each Writer?

 Don't understand the question.

> 
> Is there a better way to write this sort of code?
> 
> --
> Regards Philip Shearer
> 
> eMail: philips@asiatech.co.za
> Tel  +27 (0)11 784 8925
> Fax  +27 (0)11 784 8919

-- 
================
Bil@LambdaCS.com

http://www.LambdaCS.com
Lambda Computer Science 
555 Bryant St. #194 
Palo Alto, CA,
94301 

Phone/FAX: (415) 328-8952
=====================================================
			Program Design

There is a small number of high-level design strategies which have been
discussed in several books. [fn: "Programming with Threads", SunSoft Press;
"Multithreaded Programming with Windows NT", Prentice Hall.] Notably these
names are not used completely uniformly. They are:

	� Master/Slave: One thread does the main work of the program,
creating other threads to help in some portion of the work.

	� Master/Slave (Thread per Request): One thread listens for
requests, then creates a new thread to handle each request.

	� Master/Slave (Thread per Client): One thread listens for new
clients to attach, then creates a new thread to handle each client. The
thread is dedicated to its client, doing work only for that client.

	� Produce/Consumer (Work Queue or Workpile): Some threads create
work requests, and put them on a queue. Other threads take the work requests
off of the queue and execute them.

	� Dogpile: Similar to the workpile, but instead of maintaining a
queue, all the threads look for work directly.

	� Pipeline: Each thread does some work on a task, then passes the
partially completed task to the next thread.

In the discussion below, we will elaborate on each of the designs and
include some sample code. All of the code will be based on a client/server
program which takes in requests from a socket, processes them, and sends
replies back out over the same socket fd. The complete code for three
versions of the program (Thread per Request, Producer/Consumer, and
non-threaded) are on the web site.

Master/Slave

The master/slave design is the most obvious for many kinds of tasks. In its
most elemental form, it will be implemented by a library and the programmer
will not even be aware of there being multiple threads. A matrix multiply
routine (such as Dakota Scientific's) may well spawn a set of threads to do
the work, but all the programmer knows is that she called matrix_multiply().

Master/Slave (Thread per Request)

This is a M/S design for client/server programs. The master thread will do
the listening. In the fragment of the socket program below, each time a new
request comes in from a client, the main thread spawns off a thread to
handle that request. The main thread then returns to its accept() loop while
the thread works on the request independently, exiting when it's done.

Code�Example�8-13	Master/Slave Socket Example

main()

{ 

...

while(TRUE)

 {newsockfd = accept(sockfd, &cli_addr, &clilen);

  pthread_create(NULL, &thr_attr, process_request, newsockfd);

 }

}

void *process_request(void *arg)

{

 read(mysocfd, data, LENGTH);

 result = process_data(data);

 write(mysocfd, result, LENGTH);

 close(mysocfd);

 pthread_exit();

}

While this design has some positive aspects to it, e.g. simplicity and
directness, it also admits to some drawbacks. The cost of thread creation is
not going to be significant unless the task itself is very short (<
10ms). Of more significance is that the programmer has no control over the
number of threads running at any one time. Should there be a sudden spike in
the number of requests, there will be a equal spike in the number of
threads, causing performance degradation due to the excessive number of
threads competing for the same locks, CPUs, and other resources.

Rewriting the program to limit the number of threads would be somewhat ugly, 
and there are better ways of handling the problem. This is probably not a good 
design for any program!

Producer/Consumer

 In the producer/consumer model, the programmer can exert full control over
the number of threads with very little effort. The threads may be created at
startup time, and then left to wait for work appearing on the queue. Should
some of the threads never be used, it will be no great cost -- probably
immeasurable. Should there be too many incoming requests, they can be placed
on the queue and handled when convienent.

Code�Example�8-14	Producer/Consumer Socket Example

main()

{ 

 for (i=0; i<N; i++)

  pthread_create(NULL, &thr_attr, process_request, NULL);

 ...

 while(TRUE)

   {newsockfd = accept(sockfd,  &cli_addr, &clilen);

    add_to_queue(newsockfd);

   }

}

void *process_request()

{

 ...

 while(TRUE)

  {socfd = get_from_queue();

   read(socfd, data, LENGTH);

   result = process_data(data);

   write(socfd, result, LENGTH);

   close(socfd);

  }

}

An important aspect of the work queue is that you can allow the queue to
grow to any length you deem appropriate. If your clients block, waiting for
the results of query 1 before issuing query 2, then allowing the length of
the queue to grow to the number of clients will assure you that requests
will never be lost, and you can maintain peak efficency.

If clients are able to issue unlimited overlapping requests, then you have
no choice. At some point you must begin rejecting requests. However, as long
as the average rate of incoming requests is below what your server can
handle, then by allowing the queue to grow up to some modest limit, you can
effectively buffer burst traffic while retaining peak efficency.

Dogpile

The dogpile (pigpile for those in the east) is my name for the same program
as above, only that each thread waits to do an accept itself. There is no
producer thread which calls accept() and puts work onto the queue for other
threads. All the threads take turn calling accept(), and then doing the work
directly. In the steady state situation, there should be no difference in
efficency between the work queue and the dogpile. But where the work queue
can neatly handle burst traffic at user level, the dogpile would expect the
kernel to queue those requests for it -- - probably not a good thing.

Code�Example�8-15	
main()

{ 

 for (i=0; i<N; i++)

  pthread_create(NULL, &thr_attr, process_request, NULL);

}

void *process_request()

{

 ...

 while(TRUE)

  {pthread_mutex_lock(&m);

   newsockfd = accept(sockfd,  &cli_addr, &clilen);

   pthread_mutex_unlock(&m);

   read(mysocfd, data, LENGTH);

   result = process_data(data);

   write(mysocfd, result, LENGTH);

   close(mysocfd);

  }

}

Pipeline

The pipeline model is based directly on the same work model that is used in
CPUs and on factory floors. Each processing element will do a certain amount
of the job, and then pass the partially completed task on to the next
element. Here the processing elements are threads of course, and each thread
is going to do a portion of the task, then pass the partial results on to
the next thread.

Code�Example�8-16	
main()

{ 

  pthread_create(NULL, &thr_attr, process_request_a, NULL);

  pthread_create(NULL, &thr_attr, process_request_b, NULL);

  ...

}

void *process_request_a()

{

 ...

 while(TRUE)

  {newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, 
&clilen);

   read(mysocfd, data, LENGTH);

   result_a = process_data_a(data);

   add_queue_b(result_a);

  }

}

void *process_request_b()

{

 ...

 while(TRUE)

  {result_a = get_from_queue_a();

   result_b = process_data_b(result_a);

   write(mysocfd, result_b, LENGTH);

   close(mysocfd);

  }

}

We can certainly see where this would be valuable for simulations where what
you're simulating is a pipeline. For other situations, it's not so clear. In
silicon and on factory floors, specialization is important. One section of a
chip can only execute a single task (the instruction fetch unit can only
fetch instructions, never decode them), and it takes time for a workman to
put down a wrench and pick up a paint brush.

This is not so for threads. It is actually easier for one thread to execute
an entire operation on some input than to do a little work, package up the
partial result and queue it for another thread. It's easier, faster, and the
programming is simpler. Although a number of programs have been suggested
which use this paradigm, it is not clear that any of these are superior to
using one of the other designs.

Master/Slave (Thread per Client)

The final model is also a somewhat questionable one. In the Thread per
Client model, each client would have a thread devoted to it, and that thread
would remain inactive the vast majority of the time. The advantage of having
a thread devoted to an individual client is that the thread could maintain
state for that client implicitly by what's on the stack and in thread
specific data. While this does save the programmer the effort of
encapsulating that data, it's unclear (to me) that it's worth it. None the
less, a number of database vendors are interested in this model and they do
have some pretty clever folks there.

Code�Example�8-17	
main()

{ 

...

while(TRUE)

 {newsockfd = accept(sockfd, &cli_addr, &clilen);

  pthread_create(NULL, &thr_attr, process_requests, newsockfd);

 }

}

void *process_requests()

{

 ...

 while(TRUE)

  {read(mysocfd, data, LENGTH);

   if (done(data)) break;

   result = process_data(data);

   write(mysocfd, result, LENGTH);

  }

}

			

 We'll consider these last two as interesting possible designs that need some 
practical fleshing out.



  reply	other threads:[~1996-12-06  5:00 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1996-12-06  5:00 pthreads and sockets philip Shearer
1996-12-06  5:00 ` Bil Lewis [this message]
1996-12-06  5:00 ` Bart Smaalders
1996-12-09  5:00 ` Thilo Kielmann
1996-12-13  5:00   ` New version of ACE available Douglas C. Schmidt
read-only archive

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox