views:

739

answers:

2

Hey all,

I'm thinking about making repeated calls (spinning) to QueryPerformanceCounter in two threads that will be active at the same time. I'm not sure if this is really an issue as I've not seen anything written about it but is QueryPerformanceCounter thread safe?

Thanks

A: 

It depends on where your argument to QueryPerformanceCounter lives. If it is a shared variable between the two threads, then it doesn't sound like the function is thread-safe.

So instead I recommend that each thread have its own LARGE_INTEGER to pass to your calls to QPC. Each call is independent of the other, and should update the respective LARGE_INTEGERs appropriately.

The MSDN article on this function also hints at setting an affinity mask if you are in a multi-processor environment.

Brian
+1  A: 

I'm thinking about making repeated calls (spinning) to QueryPerformanceCounter in two threads that will be active at the same time.

Oog. Think about what you're doing and how many processors are available. If you have one processor, this will not work: they can't be "active at the same time" because QueryPerformanceCounter doesn't yield control from one thread to another. I am fairly sure that thread-switching in win32 with single processors has timing granularity on the order of 1msec.

If you have multiple processors, you can get glitchy results (theoretically -- I don't have a multiprocessor PC so haven't observed this myself). More fun discussion of QPC can be found on the internet (see Raymond Chen's blog for instance)

If you really want to spin-wait for optimizing timing, I'd suggest you ask the best way to do this on one of the game programming forums where there are experts on such things.

Jason S