Thread Class

New to FreeBASIC? Post your questions here.
Post Reply
warsem
Posts: 2
Joined: Sep 22, 2022 10:26

Thread Class

Post by warsem »

Hi,

How i can give to CreateThread my sub without error? It id my first try in FreeBasic.
Help me please.

Code: Select all

TYPE TThread

  terminated AS INTEGER

  handle AS ANY PTR

  delay AS INTEGER

 

  DECLARE CONSTRUCTOR()

  DECLARE DESTRUCTOR()

  DECLARE SUB mainloop(param as Any PTR)

 

END TYPE

 

CONSTRUCTOR TThread()

  this.handle = THREADCREATE(@mainloop,0)

END CONSTRUCTOR

 

DESTRUCTOR TThread()

  this.terminated = true

END DESTRUCTOR

 

sub TThread.mainloop(param as Any PTR)

  do

    if terminated = true then exit do   

    

    

    sleep delay, 1

  loop

end sub
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Thread Class

Post by fxm »

'TThread.mainloop()' must be a static procedure (not a non-static procedure like a normal member method).
If in the body of 'TThread.mainloop()', you want to use a reference to the instance of TThread (as 'This'), you must pass it through the 'param' parameter and reconstitute it.

Your example corrected:

Code: Select all

TYPE TThread
  terminated As Boolean = False
  handle As Any Ptr
  delay As Integer = 20
  Declare Constructor()
  Declare Destructor()
  Declare Static Sub mainloop(Byval param as Any Ptr)
End Type

Constructor TThread()
  This.handle = Threadcreate(@TThread.mainloop, @This)
End Constructor

Destructor TThread()
  This.terminated = True
End destructor

SUB TThread.mainloop(Byval param as Any Ptr)
  Dim Byref AS TThread this = *Cptr(TThread Ptr, param)
  Print "thread started"
  Do
    If this.terminated = True Then Exit Do  
    Print "*";
    Sleep this.delay, 1
  Loop
  Print
  Print "thread terminated"
End Sub

Scope
  Dim t As TThread
  Sleep 3000, 1
End Scope

Sleep
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Thread Class

Post by fxm »

warsem wrote: Sep 22, 2022 10:31 How i can give to CreateThread my sub without error? It is my first try in FreeBasic.
Welcome to the forum !
If you are learning FreeBASIC starting with threads, it's not the easiest !
warsem
Posts: 2
Joined: Sep 22, 2022 10:26

Re: Thread Class

Post by warsem »

fxm,
Big thanks, bro.
I have experience with VBS and Delphin. I need learn just a syntax.
Post Reply