At school we started multithreading last week and we already are on multiprocessing now, I am getting a little lost on it so I am going to explain the problem to you.
For an exercise we must make a casino game simulator which simulates 10000 games so that we can know how often the casino wins the game.
So I coded the simulator, and I’ve got 5 methods to run a game :
static void game(Croupier croupier)
{
croupier.createNewCardDeck();
croupier.shuffleCards();
croupier.giveCardsToPlayers();
croupier.countPlayerPoints();
croupier.displayResults();
}
If I call game in a classic for loop of 10000 iterations it runs ok, takes approx 2 seconds, and the bank wins 50% of times.
If I use Parallel.For, it crashes on shuffleCards, because (I think) multiple processes are trying to edit the same pack of cards at the same time.
My first idea was to put a Mutex on my shuffleCards, but it would slow down the simulation, when the point of using Parallel programming was to increase speed. So I thought to separate data on the different processes ( so that instead of 10000 iterations, I do 2500 on 4 processes, every loop having its own croupier, players, cards etc…)
What do you think would be the best way of resolving this problem ? Have you got any simple tutorial that explains how to deal with parallel work which uses the same data ? Which solution would you choose ?
Thanks
Edit : ShuffleCard method
List<Card> randomList = new List<Card>();
Random r = new Random();
int randomIndex = 0;
while (_cards.Count > 0)
{
randomIndex = r.Next(0, _cards.Count); //Choose a random object in the list
randomList.Add(_cards[randomIndex]); //add it to the new, random list
_cards.RemoveAt(randomIndex); //remove to avoid duplicates
}
return randomList;
So yes _cards being a private property of croupier (which calls this._cards = shuffleCards() , every process have the same card list
Your idea is the way to go: Give each “processing unit” (i.e. thread, task) its own game table (croupier, players, cards). Just like in a real casino you can have as many game tables as you want, playing all at the same time, indepently from each other because they do not share any data. Whenever a game is finished, the results is transferred to the bank (of which you have only one). So the only thing that must be synchronized (with a criticial section) is the aggregation of the results into the bank.
This example is the perfect trivial example for parallel programming, because the real world can rather intuitively be modeled into the corresponding classes and algorithms.