I'm creating a turn-based strategy game in C# and XNA. I want to add multithreading so that on opponent's turn, the player may move the map and interact with the game normally while the AI computes its movement.
The AI thread (the secondary thread) is run whenever the opponent has to make a choice. That thread uses generic lists Map (List<Node>, contains all the tiles of the battlefield) and Units(List<Unit>, contains information on all units). It only reads information, it does not modify anything within Map or Units and it does not read or modify any other global variables. The result of AI's actions is stored in a class called AIResult, that looks like this:
public class AIResult{ bool ComputationCompleted; bool WillAttack; Unit EnemyUnitWhoWillDoAction; Node WhereToMove; Unit WhatToAttack; ...}
At the end of the AI thread's computations, it does this:
lock (ar){ ar = new AIResult(...);}return;
where ar is a global variable of type AIResult.
The game's main thread then regularly checks the AIResult like this:
lock (ar){ if (ar.ComputationCompleted) { ... apply it to the game, eg. move units, attack things ... }}
My question is:
1. Is it safe to read data from global variables if both threads access those variables at the same time? (AIThread to find the location of units and tiles to avoid, main thread to draw the map on screen...) If not, is it sufficient to create a clone of the Map and Units lists and use those in the AIThread?
2. Does the lock mechanism as I used it above provide protection for the AIResult? i.e. is that safe? or useless?