I have a server and a client program. The server program runs all the time waiting for requests from clients. For the server to respond to each client it takes 5 seconds using the sleep() function.
On the multithreaded version if I invoke two clients at the same time it takes about 5 seconds for each to get a response. The same test gives 5 secs for the first client and 10 to the second client in the non-multithreaded version. Something to be expected obviously. Though there is some problem. The processor is a single core Athlon!
How is it possible for the multithreaded server module to run faster than the non-threaded when the core on the cpu is only one?
Because you are simulating the “work” by sleeping. So the scheduler need only put one thread to sleep for 5 seconds; afterwards it is free to “service” another thread.
In short, you aren’t using the CPU so in theory you could service a lot of clients this way. Now if you were to do something CPU-bound for 5 seconds, you would see the difference.
The same would happen if the “work” would be
I/O. Since the CPU isn’t actually involved, many many threads appear to work concurrently.