I'm kinda new to C++ Multithreading, and I'm keeping it simple right now. I will keep things simple and write psuedo-code. I'm making a Turn Based Strategy Game but let's keep it at Chess for now.
I have a basic draw thread and update thread.
function DrawThread CurrentScreen Drawn end function LogicThread CurrentScreen Update end
Both of these functions run in their seperate threads. Now I've run into a few problems.
For example: My pieces (units) are stored in a vector in the CurrentScreen
Class MapScreen public: GetPieces returns VectorOfpieces private: VectorOfpieces end
The draw thread constantly draws the Chess pieces.
function Drawn for each chesspiece in VectorOfpieces draw chesspiece end end
I have a cursor that moves grid-based and on, for example, ENTER checks if there is a Chess piece underneath it. (I've omitted any other code that has nothing to do with it)
function PollInput if KeyPressed is ENTER CheckUnderNeath end end function CheckUnderNeath for each chesspiece in MapScreen.GetPieces if chesspiece position is cursor position return chesspiece end end end
Now as you might have guessed this Cursor update is in the other thread
function Update Cursor PollInput end
And as you might have seen coming miles away, both threads will eventually end up using the same vector at the same time, causing a crash.
Is there any easy implementation to fix a problem like this, as my 2-3 problems right now are eventually down to this problem, threads bumping heads.
What bothers me is this crash isn't consistant. Because it's a vector I will get a "map/set iterator not dereferencable" error.
I'd appreciate a C++ answer eventhough my question was in Psuedocode. Thanks in advance!
TL:DR One thread tries to update the position of the same pointer the other tries to draw.