Hey guys

Hey guys,

How do I create thread-local variables in Delphi? Do I use some class or attribute for flag that the variable is thread-local? Do I use "threadvar" modifier for this purpose?

Thanks in advance :D

Comments

  1. Yes, threadvar are how to create thread-local variables. But they are global variables, not tied to particular class.
    Be aware that threadvar have a cost: each threadvar will consume some resource for all threads, even if it is not used.
    And note also that there is no mean of automatic releasing the memory used by a threadvar: for instance, a string, an interface or a dynamic array won't be released automatically (as a standard var) when the thread finishes. You have to release the memory by hand.

    ReplyDelete
  2. what is the benefice of a threadvar against a TThread member ? I'm not a 100% OOP man, but I don't remember any case where I need a per thread global var.

    BTW Sytem.Threading TTask class use :
     class threavar FCurrentTask: TTask

    ReplyDelete
  3. A class threadvar is just a global variable in disguise. ;) Just hide the global variable within the class type namespace...
    Sometimes, a global threadvar is needed, if you need to retrieve, e.g. the execution context. I use a threadvar e.g. to store the REST request context, where it is executed outside the scope of the TThread (which is part of the protocol implementation, so several TThread classes may appear).

    ReplyDelete

Post a Comment