Code:
'______________________________________________________________________________ ' ' WorkerThread Example ' ' Spawns a second "worker" thread and demonstrates synchronizing variables ' between each thread using a critical section object and a couple of MACROs. ' ' Posted By Kev Peel ([URL="http://www.kgpsoftware.com"]www.kgpsoftware.com[/URL]), Dec 2007. '______________________________________________________________________________ #Compile Exe #Dim All #Register None %USEMACROS = 1 ' Cuts code size. #Include "WIN32API.INC" ' Includes required API definitions. Global gCS As CRITICAL_SECTION ' Thread synchronization object. Global gnEndApp As Long ' Set to TRUE to exit the application. '------------------------------------------------------------------------------ ' Safely reads any variable type to a temporary variable and returns it. ' This function uses the global critical section variable. '------------------------------------------------------------------------------ Macro Function SafeReadVar(vVar, vType) MacroTemp vTmp Local vTmp As vType EnterCriticalSection gCS vTmp = vVar LeaveCriticalSection gCS End Macro = vTmp '------------------------------------------------------------------------------ ' Safely writes any value to the specified variable. ' This function uses the global critical section variable. '------------------------------------------------------------------------------ Macro SafeWriteVar(vVar, vValue) EnterCriticalSection gCS vVar = vValue LeaveCriticalSection gCS End Macro '------------------------------------------------------------------------------ ' Sample "worker thread" Does background stuff. '------------------------------------------------------------------------------ Function WorkerThread(ByVal dummy As Long) As Long Do If MessageBox(%HWND_DESKTOP, "Close the app?", "WorkerThread Example", %MB_OKCANCEL Or %MB_ICONINFORMATION) = %IDOK Then ' Safely assign the flag... SafeWriteVar(gnEndApp, %TRUE) ' End the thread... Exit Function End If Loop End Function '------------------------------------------------------------------------------ ' Creates a worker thread and enters a sample message loop. '------------------------------------------------------------------------------ Function PBMain Local dummy As Long gnEndApp = %FALSE InitializeCriticalSection gCS ' Spawn worker thread... Thread Create WorkerThread(0) To dummy ' Sample message loop... Do Until SafeReadVar(gnEndApp, Long) <> %FALSE Dialog DoEvents Loop DeleteCriticalSection gCS End Function