Hi guys, I have to build a dual-core processor simulator in C (it's actually a multilevel memory simulation, cache L1/L2, block substitution, etc). Thing is, I'm having a hard time figuring a way to synchronize the cores (which I'm programming as threads). Any ideas how I could do a global clock? Should I change from threads to child processes? Thanks in advance
So many options here: since you might end-up supporting complex interactions with multiple threads, you might want to consider using a "virtual clock" with a message passing "bus". This way, you'll have more time to focus on the core functionality instead of debugging the synchonization logic...
Using this technique, you can build a state-machine (see here) per "actor" thread (worst case) and worry less about mutexes/conditions. Once you've got this base, you'll be able to handle cases that show up mid-stream (e.g. "I forgot about this detail... no worries, just add a state here... don't have to re-shuffle my mutexes).
Also, since doing simulation is all about "virtual time" (since you can't run real-time !), then having a base architecture based on a "virtual clock" abstracts the problem to an appropriate level.
You could have a clock thread plus N processor threads. The clock thread can explicitly make calls to each processor thread to make 1 processing step. Each processor thread gets a call from the clock thread to doStep()
; it makes one step, then returns control back to the clock thread.
You could also randomize the order in which the processor threads are called to do steps so that you're more likely to catch bugs in your client code.