When we have a threadvar declared, when this variable will be initialized (the object is created)? Does it occurs at the first assignment of the var? For example:
threadvar
myThreadVar : string;
......
//inside a thread
...
myThreadVar := 'my value'; // In this point the var will be initialized?
What happens if I try to use this var outside a thread after the thread has set the value for the var? For example:
//at the main thread (application)
...
//Call the thread;
//thread finishes execution
//thread is destroyed
ShowMessage(myThreadVar); // what happens here?
The threadvars for a thread are initialized the first time their thread accesses any one of them. They are set to a default all-bits-zero value, which for strings is the empty string.
Threadvars may or may not be finalized. It depends on how much notice the RTL gets that a thread is terminating. For that reason, it’s probably best not to store any dynamically allocated types (strings included) in threadvars. Instead, use an instance variable of a
TThreadobject to store thread-specific data.The second part of your question is nonsense. It has you executing code on a thread after the thread has already terminated. There is no such thing as running code “outside a thread.” All code runs in threads. Every program has at least one thread.
Each thread has its own copy of a threadvar. No thread can read another thread’s copy, so once a thread terminates, all its threadvars are inaccessible.
Your
ShowMessagecall will display the value belonging to the current thread, not the thread that already terminated.