Threadlocal Variables

Thread-local (or thread) variables are used in multithreaded applications. A thread-local variable is like a global variable, except that each thread of execution gets its own private copy of the variable, which cannot be accessed from other threads. Thread-local variables are declared with threadvar instead of var. For example, threadvar X: Integer;

Thread-variable declarations

  • cannot occur within a procedure or function.
  • cannot include initializations.
  • cannot specify the absolute directive.

Dynamic variables that are ordinarily managed by the compilerlong strings, wide strings, dynamic arrays, variants, and interfacescan be declared with threadvar, but the compiler does not automatically free the heap-allocated memory created by each thread of execution. If you use these data types in thread variables, it is your responsibility to dispose of their memory from within the thread, before the thread terminates. For example, threadvar S: AnsiString; S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

Note: Use of such constructs is discouraged. You can free a variant by setting it to Unassigned and an interface or dynamic array by setting it to nil.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment