0

I have code that logs execution times of routines by accessing QueryPerformanceCounter. Roughly:

var
    FStart, FStop : Int64 ;
...
QueryPerformanceCounter (FStart) ; 
... <code to be measured>
QueryPerformanceCounter (FStop) ; 

<calculate FStop - FStart, update minimum and maximum execution times, etc>

Some of this logging code is inside threads, but on the other hand, there is a display UI that accesses the derived results. I figure the possibility exists of the VCL thread accessing the same variables that the logging code is also accessing. The VCL will only ever read the data (and a mangled read would not be too serious) but the logging code will read and write the data, sometimes from another thread.

I assume QueryPerformanceCounter itself is thread-safe.

The code has run happily without any sign of a problem, but I'm wondering if I need to wrap my accesses to the Int64 counters in a critical section?

I'm also wondering what the speed penalty of the critical section access is?

Johan
  • 74,508
  • 24
  • 191
  • 319
rossmcm
  • 5,493
  • 10
  • 55
  • 118

1 Answers1

1

Any time you access multi-byte non-atomic data across thread when both reads and writes are involved, you need to serialize the access. Whether you use a critical section, mutex, semaphore, SRW lock, etc is up to you.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • OK. Can I not take advantage of the fact that only one thread is ever writing to the data? Sure, another thread reading the data might read a partially updated value, but this is not of too much consequence in this application (the reading thread is always the VCL thread which is reading the data for display and it refreshes every second). What I am more worried about is conflict causing a lockup. If I need to serialize access time is important because any time spent managing the access is a timing overhead. Which of these options carries the lowest (time) overhead? – rossmcm Dec 09 '11 at 05:40
  • If all you are doing is displaying an `Int64` value and doing nothing else with it, then you do not need to serialize the data. If you were actually acting on the value, then you would have to serialize access to ensure its integrity. – Remy Lebeau Dec 09 '11 at 09:20