In: Computer Science
Task 2 [10 pts] Implementing Synchronization of Chat Client Threads Using Semaphores
In c language
In this task, a character buffer should be created (e.g., char buf[500]) in the server which is shared among threads that are created to handle communication with clients. Specifically, when the server receives a message (a string) from a client, the server should (1) store the message in the buffer, (2) broadcast the message to all connected clients, and (3) clear the buffer. Make sure that this process (1)~(3) should be done in a synchronized manner. In other words, when the server is accessing the shared buffer to broadcast the message in the buffer, other threads should wait until the current thread that is accessing the shared buffer finishes this process using a semaphore.
In evaluating your work, we will look at your source code to see if semaphores are used appropriately to synchronize the threads of the server.
Considering Following Semaphores:
Counting Semaphores - 'Full' = 0 (number of filled
slots of buffer)
'Empty' = 500 (number of empty slots of buffer)
Binary Semaphore - 'S' = 1
Consider Following Variable Declarations:
int in = 0; <-- Stores the index value where
the next incoming message have to be stores in buffer
int out = 0; <-- Stores the index value from
where the message have to be broadcasted to other clients.
Following shall be the pseudo code to understand the use of semaphores in the given scenario
Client Function:
client(string msg) {
down(empty); or wait(empty);
down(S); or wait(S);
// Critical Section starts
buff[in] = msg;
in = (in + 1) % 500;
// Critical Section ends
up(S); or signal(S);
up(full); or signal(full);
}
Server Function:
server () {
down(full); or wait(full);
down(S); or wait(S);
// Critical Section starts
msg_to_broadcast = buff[in];
out = (out + 1) % 500;
// Critical Section ends
up(S); or signal(S);
up(empty); or signal(empty);
}