M Schenkel
M Schenkel

Reputation: 6364

Are global atomic variable used inside TIdHTTPServer.OnCommandGet threadsafe?

I am trying to get a better understanding of the Delphi Indy Server and ThreadSafe variables.

Lets say I want a simple counter of the number of "hits" to my Delphi Indy webserver. So I declare a global integer

var: GlobalWebHits: Integer

And inside my handler for TIdHttpServer.OnCommandGet I increment it:

procedure MyWebServer.CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  GlobalWebHits := GlobalWebHits+1;
  .....
end;

It this implementation ok with regards to thread safety? Is it possible that two threads try to update GlobalWebHits at exactly the same time?

Should the incrementing be wrapped in a Critical Section?

Upvotes: 0

Views: 268

Answers (1)

David Heffernan
David Heffernan

Reputation: 613242

There is no such thing as an atomic variable. Operations can be atomic, or not.

GlobalWebHits := GlobalWebHits+1;

This one is not atomic. It has separate read, modify and write stages.

You could use a critical section but it is simpler and more efficient to use an atomic operation:

AtomicIncrement(GlobalWebHits);

or

TInterlocked.Increment(GlobalWebHits);

or

InterlockedIncrement(GlobalWebHits);

depending on which Delphi version you use.

Upvotes: 2

Related Questions