RBA
RBA

Reputation: 12584

Enumerated type - thread safety

I'm having an argue with a colleague about thread safety on enumerated types. Having the following simple enumerated type:

type Suit = (Club, Diamond, Heart, Spade);

and declared as a variable inside a class as in the following dummy code:

type 
TTest = class
private 
  FSuit: Suit;
  function SetSuit(aValue: Suit);
public
  property GimmeSuit: Suit read FSuit;

.....

function SetSuit(aValue: Suit);
begin
  FSuit:= aValue;
end;

I say that this code is thread safe, as setting FSuit variable's value is an atomic operation. I'm wrong? I didn't found anything on web about this case.

Upvotes: 3

Views: 194

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

The terminology you use, threadsafe and atomic need to be clarified before this can properly be addressed.

  • Threadsafe is a vague term that has to be qualified in terms of the specific context in which it is to be applied. This is covered in great detail by Eric Lippert's classic article What is this thing you call "thread safe"?
  • An atomic operation is one that is indivisible. It appears to the rest of the system as happening at once.

In the code you have shown I assume that multiple threads are both reading and writing FSuit.

With all that in place, reading and writing FSuit is atomic, so long as it is a single byte, or aligned.

Single byte memory access is always atomic. If the enumerated type is larger than a single byte, then it must be aligned for memory read/write to be atomic. Misaligned memory access can tear. That is, the reading thread may see only part of the write because the variable straddles a cache line. The writing thread has to write part of the variable to one cache line, and then the rest to the adjacent cache line, and the reading thread might read the entire variable part way through the two stage write process.

Now, with default settings, this enumerated type will be a single byte, and the class layout will be aligned. So even read/write to larger enumerated types would be atomic.

As for whether or not your program is threadsafe, that cannot be determined from the information here. You would need to clarify what the intent was. For example, suppose that two threads wrote to FSuit, and a third thread read from it. If your program's correctness does not depend about the orderings of those memory accesses, then it is threadsafe. If its correctness does depend on the ordering, then it is not threadsafe and requires synchronisation.

Upvotes: 11

Related Questions