THREADED variables

PowerBASIC now offers a THREADED variable type for use in multi-threaded programs.  While multi-threaded programming is an advanced topic and is beyond the scope of this documentation, we'll briefly describe thread variables in PowerBASIC.

Thread variables (also known as thread-local storage or TLS) can be declared with either a THREADED statement or a DIM statement (with the THREADED scope clause).  In either case, thread variables are visible to all Subs and Functions in a program, but each thread will have its own unique copy of each of the variables.  This allows data to be shared between Subs and Functions on a thread by thread basis.  For example:

THREADED t1 AS LONG

...

FUNCTION MyThread(BYVAL x AS LONG) AS DWORD

  t1 = RND(1,x)

  ' Here t1 is unique to each thread

  CALL MySub

END FUNCTION

...

SUB MySub

  ? t1

  ' Here t1 is unique to the thread calling MySub

END SUB

Thread variables have a distinct advantage over global variables as they avoid the need to use synchronization techniques (such as a Critical Section object or Mutex) when referencing (reading or writing) from two or more threads at the same time.  In addition, all allocation and deallocation of THREADED memory is handled automatically by PowerBASIC without any need for intervention by the programmer.  However, by their nature, thread variables impose a slight, yet measurable, performance penalty as compared to other variable types.

 

See Also

Variables

Default Variable Typing

Variable Scope

LOCAL, GLOBAL and STATIC considerations