217,830 views
26 votes
26 votes
Servers can be designed to limit the number of open connections. For example, a server may wish to have only N socket connections at any point in time. As soon as N connections are made, the server will not accept another incoming connection until an existing connection is released. Please write pseudo-code to implement the synchronization using semaphore.

User Luke Cardeaux
by
3.1k points

1 Answer

19 votes
19 votes

Answer:

The pseudocode is as follows:

open_server()

connections = N

while (connections>0 and connections <=N):

if(new_client == connected):

connections = connections - 1

for i in 1 to N - connections

if (client_i == done()):

releast_client(client_i)

connections = connections + 1

Step-by-step explanation:

One of the functions of a semaphore is that, it is a positive variable whose value will never fall below 1. It is often shared among threads in order to keep a process running.

Having said that, what the above pseudocode does is that:

Once the server is opened, it initializes the number of connections to N.

When a new client, the semaphore decreases the number of connections is reduced by 1.

Similarly, when an already connected client is done, the client is released and the number of connections is increased by 1.

This operation is embedded in a while loop so that it can be repeatedly carried out.

User Gjsalot
by
2.5k points