Page 1 of 1

Is this thread safe?

Posted: Sat Apr 12, 2025 9:59 pm
by Randy Walker
I modified the sample code to have the tread kill itself. Is that a bad thing?

Code: Select all

;
; ------------------------------------------------------------
;
;   PureBasic - Thread example file
;
;    (c) Fantaisie Software
;
; ------------------------------------------------------------
;
Global thread
Procedure AlertThread(Parameter)
  
  Repeat
    Debug "Alert ! "+Str(Parameter)
    Delay(3000)
    Parameter-1
    If Parameter = 147
      KillThread(thread)
    EndIf
  ForEver
  
EndProcedure

thread = CreateThread(@AlertThread(), 154)

; MessageRequester("Info", "It will display an alert every 3 seconds."+#LF$+"Click To kill the alerts", 0) 
; KillThread(thread)
MessageRequester("Info", "Click To finish the program", 0) 
I am considering use of threads, but I want the thread to die after it completes it's task.

Re: Is this thread safe?

Posted: Sat Apr 12, 2025 10:47 pm
by mk-soft
Very Bad.

KillThread should only be used in extreme cases of errors and can lead to memory leaks.

Better ...

Code: Select all

EnableExplicit

Global thread
Global ExitThread

Procedure AlertThread(Parameter)
  ; Init resources
  
  ; Loop Thread
  Repeat
    Debug "Alert ! "+Str(Parameter)
    Delay(3000)
    Parameter-1
    If Parameter = 147
      Break
    EndIf
  Until ExitThread
  ; Release Thread resources
  
  ; Exit Thread
EndProcedure

thread = CreateThread(@AlertThread(), 154)

; MessageRequester("Info", "It will display an alert every 3 seconds."+#LF$+"Click To kill the alerts", 0) 
; KillThread(thread)
MessageRequester("Info", "Click To finish the program", 0) 

ExitThread = #True
If WaitThread(thread, 5000) = 0
  Debug "Thread hangs. KillThread"
  KillThread(Thread)
Else
  Debug "Thread Done."
EndIf

Re: Is this thread safe?

Posted: Sat Apr 12, 2025 10:48 pm
by HeX0R
A thread never has to "kill" itself, you simply let it end.
Replace KillThread(thread) with break and all is fine.

Re: Is this thread safe?

Posted: Sat Apr 12, 2025 10:56 pm
by mk-soft
And with structured data ...

Code: Select all


EnableExplicit

Structure structData
  ThreadID.i
  Exit.i
  Count.i
EndStructure

Global thData.structData

Procedure AlertThread(*Data.structData)
  With *Data
    ; Init resources
    
    ; Loop Thread
    Repeat
      Debug "Alert ! "+Str(\Count)
      Delay(3000)
      \Count-1
      If \Count = 147
        Break
      EndIf
    Until \Exit
    ; Release Thread resources
    
    ; Exit Thread
  EndWith
EndProcedure

thData\Count = 154
thData\ThreadID = CreateThread(@AlertThread(), @thData)

; MessageRequester("Info", "It will display an alert every 3 seconds."+#LF$+"Click To kill the alerts", 0) 
; KillThread(thread)
MessageRequester("Info", "Click To finish the program", 0) 

thData\Exit = #True
If WaitThread(thData\ThreadID, 5000) = 0
  Debug "Thread hangs. KillThread"
  KillThread(thData\ThreadID)
Else
  Debug "Thread Done."
EndIf