I am using Delphi TThread
to run multiple TCP connections to external devices. Incoming data is dissected and stored. Everything works OK but on reviewing my code I am having doubts whether it is thread safe or if I am just being lucky so far...
In the TThread.Execute
method, I am calling a helper function which exists in a different unit, not being a member of any TThread
or other class. The function accesses four bytes of data in a buffer, reverses the byte order and places the result in a variable of type Single
, (the external devices are Big Endian).
type
TByteBuffer = array [0 .. 255] of Byte;
function ConvBufferToSingle(Buffer: TByteBuffer; J: Byte): Single;
type
TSingleByteArray = array [0 .. 3] of Byte;
var
X: Single;
begin
TSingleByteArray(X)[3] := Buffer[J];
TSingleByteArray(X)[2] := Buffer[J + 1];
TSingleByteArray(X)[1] := Buffer[J + 2];
TSingleByteArray(X)[0] := Buffer[J + 3];
Result := X;
end;
Although this seems to work, I can't understand what happens if one (or more) threads enter this function before another thread has exited. I have read articles on Thread Safe vs. Re-Entrant code, but I am still not sure how to verify that the code is thread safe.
When the function is called, I believe that the parameters are pushed onto the stack. This would happen for each TThread
entering the function, but what happens in the code addressing those variables confuses me.
For peace of mind, is it better practise to turn the function into a method of the thread class?