2

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?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 7
    The function you have shown is perfectly thread-safe, as long as each thread is calling it with its own `TByteBuffer` that is not being shared with other threads (or, if shared, that access to it has been adequately synchronized between threads). – Remy Lebeau Nov 03 '22 at 15:46
  • Methods are just functions that have additional hidden parameter. There is nothing in methods that would make them more thread-safe or unsafe than functions. It all depends on how the function or method is written and what kind of shared data, if any, it accesses. If the function or method does not access any shared data directly, like your does not, then on its own it is thread-safe. However, if the data you pass as parameters is shared between multiple threads, then thread safety of the code will depend on that broader context, not just function itself, like Remy already mentioned. – Dalija Prasnikar Nov 04 '22 at 11:39
  • It is a bit unclear what you mean by "This would happen for each TThread entering the function, but what happens in the code addressing those variables confuses me." About which variables are you talking about here, which code, and at which time? – Dalija Prasnikar Nov 04 '22 at 11:43

0 Answers0