In a recent bout of insanity, I thought it would be cool to play around with concurrency in pure C. Nothing crazy, maybe controlling access to a shared resource and a semaphore or two for good measure. Since I assumed this would be no easy feat in C, I deciced I’d start with a problem I knew. So I went with the dining philosophers problem. Defining the Problem There are five (can be adjusted) philosophers sitting around a round table.
Let me start by saying that I’ve made this mistake on many occasions in the past. I just assume that static/shared objects are thread-safe. Things like HttpContext.Current.Cache…OOPS! A typical implementation of a cache lookup might look like this: Let’s analyze this code in a little detail. Here are the steps performed: Load the object from the Cache If the object is null (not found) Create the object and store it in the cache Return the object back to the caller To start, we should ask, what happens if 10 simultaneous requests come through attempting to get to the cache object?