Context: I have a program that needs to play some sound while displaying text at a specified interval, meaning:
Play sound
Display first text
Wait some seconds
Display more text
Wait some more
Display more text
The music needs to continue playing while the wait it taking place. I don't think I could use sleep because sleep would stop the program as a whole and would interrupt the music ...
My current approach is to play the sound in the main program and rely on a timer to implement the wait as illustrated below:
Type
TMyClass = class
private
fDone : Boolean;
fTimer : TTimer;
Procedure OnTimer(Sender: TObject);
Procedure WaitForTwoSeconds;
end;
Assume the constructor has initialized the timer and assigned OnTimer as an event handler to OnTimer. The body of this method sets fDone to true as seen below:
Procedure MyClass.Timer1StopTimer(Sender : TObject);
begin
fDone := true;
end;
Lastly, the method
WaitForTwoSeconds will assign a string to a variable, loop waiting for fDone to be true and then assign a second string to the local variable. The example is silly, I know, but it illustrates the problem I'm trying to solve:
Procedure MyClass.WaitTwoseconds;
var S: String;
begin
fDone := false;
fTimer.Interval := 2000;
S := 'This is the first sentence';
fTimer.Start;
//Now wait on the timer to be done.
While Not fDone do Application.ProcessMessages;
S := 'This is the second sentence';
end;
My question: Since fDone is not protected by semaphores, there will be a potential race condition between the thread within the timer and the main thread. Does it matter? Do I need to worry about it, and if so what would be the best way to handle this? Do I need to have recourse to actual threads?