BarryG wrote: Mon Apr 22, 2024 8:53 am
Seems to work fine here?...
Tried it multiple times here before I wrote the post, most of the time the code was stable, but at least two times I got an memory access error when closing the window
Today I tested your code again 30+ times with no error, not sure if the PB IDE (or myself) was in an unstable state some days before
Aborting an thread may not be useful while the app is running but I usually have such a feature for a clean exit of a program. I'd never use 'End' to shut down all unfinished threads nor 'KillThread' (because itself is unstable). Waiting until all threads have been finished can be annoying for the user.
Nothing new here, only a counter to see how many threads get killed when ending the program:
Code: Select all
; Enable thread-safety in Compiler Options.
Global ActiveThreads
Global param$
Global semaphore=CreateSemaphore()
Procedure MyThread_One(param)
Protected Dim a.q(99999999)
ActiveThreads+1
Debug "init..."
time$=PeekS(param)
SignalSemaphore(semaphore)
Debug "T1 -> "+time$ ; Should show the time.
Sleep_(60000)
ActiveThreads-1
Debug "done..."
EndProcedure
Procedure MyThread_Two(param)
ActiveThreads+1
date$=PeekS(param)
SignalSemaphore(semaphore)
Debug "T2 -> "+date$ ; Should show the date.
Sleep_(60000)
ActiveThreads-1
EndProcedure
OpenWindow(0,400,200,170,80,"test",#PB_Window_SystemMenu)
ButtonGadget(0,20,20,130,30,"Click this repeatedly")
AddKeyboardShortcut(0,#PB_Shortcut_Return,0)
AddWindowTimer(0,0,500)
Repeat
Select WaitWindowEvent()
Case #PB_Event_Gadget,#PB_Event_Menu
p1$=FormatDate("%hh:%ii:%ss",Date())
CreateThread(@MyThread_One(),@p1$)
WaitSemaphore(semaphore)
p1$="" ; Required here.
p2$=FormatDate("%yyyy/%mm/%dd",Date())
CreateThread(@MyThread_Two(),@p2$)
WaitSemaphore(semaphore)
p2$="" ; Required here.
Case #PB_Event_Timer
; SetWindowTitle(0,"t"+Chr(105+6*t&1)+"ck, "+Str(GetProcessMemoryUsage(GetCurrentProcess_()))+" MByte")
t+1
Case #PB_Event_CloseWindow
Debug "Active threads: "+ActiveThreads
End; (see notes above)
EndSelect
ForEver
[code]