FutureBasic Logo

<<    Index    >> FutureBasic 5

threadbegin   statement

threadbegin fn name [, parameter& [, stackMin&]]

What exactly is a thread? It is a function that performs a task. The difference between a threaded function and any other function is that the threaded version runs in the background. Your program (and other running processes) advance without interruption as the threaded task is performed.
There are many reasons for using threaded functions. One that is becoming popular relates to functions that access Internet connections. Since logging in and downloading often take a good bit of time, it makes sense to hand such a task to a threaded function and go on about your business. You might handle other tasks like complex calculations, lengthy sorts, or time-consuming file loads.
When a threaded function is called, it executes without stopping until it is complete -- just like any other function. But at some point inside of the function, you yield to other processes by calling threadstatus. The threadstatus statement allows other actions to take place and optionally sets a timed delay for the number of ticks that should elapse before your function regains control.
The parameter& passed to a thread may be any long integer required by your program. It is for your use. If a parameter is sent, you should accept it in the named local funtion. For instance, if a parameter were used in the example below, we would create the funtion with local fn myThread(param as long) instead of just plain local fn myThread.
If the stackMin& parameter is omitted, FutureBasic sets a minimum stack space of 131072 bytes (128K). You may experiment with larger or smaller values for your specific needs.

This simple example creates a thread that prints a string of text, piece by piece, in a for/next loop. The threadstatus call installs a callback time of 10 ticks which makes the text appear slowly. You can type into the edit field as the threaded text is placed on the screen.
local fn myThread
   dim t$,x, abort
   t$ = "Hello. I am a thread. "
   t$ += "I execute in the background."
   for X = 1 to len(t$)
print @(1,1) left$(t$,x);
abort = threadstatus(10)//call me in 10 ticks
if abort != 0 then exit fn
end fn

window 1
text _sysfont,12,0,0
print@(1,3)"Type into the edit field"
edit field 1,"",(8,80)-(200,100)
threadbegin fn myThread
until 0

See Also:
threadstatus; timer; on timer