changeset 14358:4d3d74ffee51 draft

(svn r18913) -Fix (r18892): the deadlock was still possible
author glx <glx@openttd.org>
date Mon, 25 Jan 2010 00:43:51 +0000
parents 8c37cdc73f7f
children 78b6c93938a7
files src/sound/win32_s.cpp
diffstat 1 files changed, 14 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/src/sound/win32_s.cpp
+++ b/src/sound/win32_s.cpp
@@ -38,16 +38,18 @@
 static DWORD WINAPI SoundThread(LPVOID arg)
 {
 	MSG msg;
-	WAVEHDR *hdr;
 
 	while (_waveout != NULL) {
-		for (hdr = _wave_hdr; hdr != endof(_wave_hdr); hdr++) {
+		for (WAVEHDR *hdr = _wave_hdr; hdr != endof(_wave_hdr); hdr++) {
 			if ((hdr->dwFlags & WHDR_INQUEUE) != 0) continue;
 			MxMixSamples(hdr->lpData, hdr->dwBufferLength / 4);
 			if (waveOutWrite(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR) usererror("waveOutWrite failed");
 		}
-		GetMessage(&msg, NULL, MM_WOM_DONE, MM_WOM_DONE);
+
+		/* Wait for the device to be closed or ready to play new data. */
+		GetMessage(&msg, NULL, MM_WOM_CLOSE, MM_WOM_DONE);
 	}
+
 	return 0;
 }
 
@@ -63,8 +65,10 @@
 
 	_bufsize = GetDriverParamInt(parm, "bufsize", (GB(GetVersion(), 0, 8) > 5) ? 8192 : 4096);
 
+	/* Create the sound thread in suspended state because we are not ready to play anything. */
 	if (NULL == (_thread = CreateThread(NULL, 8192, SoundThread, 0, CREATE_SUSPENDED, &_threadId))) return "Failed to create thread";
 
+	/* Open the sound device, it will send messages to sound thread. */
 	if (waveOutOpen(&_waveout, WAVE_MAPPER, &wfex, (DWORD_PTR)_threadId, 0, CALLBACK_THREAD) != MMSYSERR_NOERROR) return "waveOutOpen failed";
 
 	MxInitialize(wfex.nSamplesPerSec);
@@ -72,6 +76,7 @@
 	PrepareHeader(&_wave_hdr[0]);
 	PrepareHeader(&_wave_hdr[1]);
 
+	/* We are now ready to play sound, so resume the sound thread. */
 	ResumeThread(_thread);
 
 	return NULL;
@@ -81,13 +86,16 @@
 {
 	HWAVEOUT waveout = _waveout;
 
+	/* Break the sound thread loop, but the thread can still be waiting for a message. */
 	_waveout = NULL;
-	WaitForMultipleObjects(1, &_thread, true, INFINITE);
 
-	waveOutReset(waveout);
+	/* Stop the playback (if any) and close the device. This will unlock the thread if it's waiting for a message. */
+	waveOutReset(waveout); // Triggers MM_WOM_DONE message if there were pending playbacks.
 	waveOutUnprepareHeader(waveout, &_wave_hdr[0], sizeof(WAVEHDR));
 	waveOutUnprepareHeader(waveout, &_wave_hdr[1], sizeof(WAVEHDR));
-	waveOutClose(waveout);
+	waveOutClose(waveout); // Triggers MM_WOM_CLOSE message.
 
+	/* Now we can wait for the sound thread to finish because we know it will. */
+	WaitForMultipleObjects(1, &_thread, true, INFINITE);
 	CloseHandle(_thread);
 }