koger
asked on
Threadsafe function
Lets say I have a simple function which don't interacts with the VCL, e.g. adding two numbers.
If I call this function the same time from two threads, would that cause an error.
Would it make a differens if the function creates an local object and frees it after use. Then two objects should be created I guess.
Please higher my thread knowledge :)
If I call this function the same time from two threads, would that cause an error.
Would it make a differens if the function creates an local object and frees it after use. Then two objects should be created I guess.
Please higher my thread knowledge :)
You can call the same function from 2 different threads as long as the function is thread-safe. Functions like Pos(), IntToStr() and Length() are safe. The same counts for Objects. Each thread can create its own objects. E.g. TStringlist and TMemoryStream.
Use threadvar directive instead of var.
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-variable declarations
cannot occur within a procedure or function.
cannot include initializations.
cannot specify the absolute directive.
Reference-counted variables (such as long strings, dynamic arrays, or interfaces) are not thread-safe, even if they are declared with threadvar. Do not use dynamic thread variables, since there is in general no way to free the heap-allocated memory created by each thread of execution. Finally, do not create pointer- or procedural-type thread variables.
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-variable declarations
cannot occur within a procedure or function.
cannot include initializations.
cannot specify the absolute directive.
Reference-counted variables (such as long strings, dynamic arrays, or interfaces) are not thread-safe, even if they are declared with threadvar. Do not use dynamic thread variables, since there is in general no way to free the heap-allocated memory created by each thread of execution. Finally, do not create pointer- or procedural-type thread variables.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.