Implementing a Server Cache

  • 0

    Suppose there is a caching system implemented on server which caches the most recently used web pages. We make use of this cache to service queries from incoming requests from the clients. Now, we have a thread on the server which listens for cache update events. This thread updates the cache in response to these events.
    Now, you need to implement a synchronization system on the server such that multiple threads requesting service requests from the server should be able to read the data without any problem. But, whenever the update thread has to update the cache, it should get exclusive access to the cache.

  • 0

    The solution to this problem is similar to a general Reader-Writer Synchronization Problem.

    A sample pseudocode is given below. We make use of two semaphores wrt and mutex both initialized to 1. The readcount is initialized to 0.

    The structure of the writer process/thread takes this form:

    do {
    wait (wrt) ;
    // writing is performed
    signal (wrt) ;
    } while (true)

    The structure of the reader process takes this form:

    do {
    wait (mutex) ;
    readcount ++ ;
    if (readercount == 1) wait (wrt) ;
    signal (mutex);
     // reading is performed
    wait (mutex) ;
    readcount - - ;
    if redacount == 0) signal (wrt) ;
    signal (mutex) ;
    } while (true)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.