Showing posts with label Agents. Show all posts
Showing posts with label Agents. Show all posts

Tuesday, May 22, 2012

Playing PingPong with STM - Refs and Agents

PingPong is a classic example where 2 players (or threads) access a shared resource - PingPong Table and pass the Ball (state variable) between each other. With any shared resource, unless we synchronize the access, the threads can run into potential deadlock situation.

The PingPong algorithm is very simple

if my turn {
     update whose turn is next
     ping/pong - log the hit
     notify other threads
} else {
    wait for notification
}



Let's take an example and see how this works! Here is our Player class, which implements Runnable and takes in the access to the shared resource and a message