Home Thread safety read InterlockedIncremented value
Reply: 0

Thread safety read InterlockedIncremented value

user765
1#
user765 Published in May 25, 2018, 9:02 am

In my application several threads increment some counter and only one reads this value (main thread). As far I know, reading 32-bit value is thread-safe if it is aligned by double word, so I use such code:

{$A8}
TMyStat = class
private
  FCounter: Integer;
public
  procedure IncCounter;
  property Counter: Integer read FCounter;
...

procedure TMyStat.IncCounter;
begin
  InterlockedIncrement(FCounter);
end;

But I'm not sure that it's safe to mix Interlocked functions and direct access to value.

Should I use InterlockedCompareExchange instead?

function TMyStat.GetCounter: Integer;
begin
  Result := InterlockedCompareExchange(FCounter, 0, 0);
end;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.336892 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO