Is there a way to know how much time passed from when I called WaitForSingleObject function untill it returned?
or that the only way of knowing is by using some kind of a timer?
Just store current time before calling WaitForSingleObject(). Then compare to time when it returns.
From http://msdn.microsoft.com/en-us/library/windows/desktop/ms725473(v=vs.85).aspx - select a function to retrieve time.
You will need to use a timer if you need to track that. The other alternative (although you won't get exact time, a timer would be better) is to call WaitForSingleObject with a small timeout value. You can check the return code to see if it is WAIT_TIMEOUT. If it is, then increment your time count by the timeout value.
GetTickCount() before and after the call. Watch out for DWORD wrap-around.
Related
I have a loop in C++ that I would like to run for a few seconds. Although the amount of work on every iteration is different, from a few microseconds to seconds, it is ok to stop between iterations. It is high-performance code so I would like to avoid calculating time difference on each iteration:
while (!status.has_value())
{
// do something
// this adds extra delays that I would like to avoid
if (duration_cast<seconds>(system_clock::now() - started).count() >= limit)
status = CompletedBy::duration;
}
What I'm thinking is maybe there is a way to schedule signal and then stop the loop when it happens instead of checking the time difference on every iteration.
BTW, the loop may exit before the signal.
I have done something similar, but in Java. The general idea is to use a separate thread to manage a sentinel value, making your loop look like...
okayToLoop = true;
// code to launch thread that will wait N milliseconds, and then negate okayToLoop
while((!status.hasValue()) AND (okayToLoop)) {
// loop code
}
The "cautionary note" is that many sleep() functions for threads employ "sleep at least" semantics, so if it is really important to only sleep N milliseconds, you'll need to address that in your thread implementation. But, this avoids constantly checking the duration for each iteration of the loop.
Note that this will also allow the current iteration of the loop to finish, before the sentinel value is checked. I have also implemented this approach where the "control thread" actually interrupts the thread on which the loop is executing, interrupting the iteration. When I've done this, I've actually put the loop into a worker thread.
Any form of inter-thread communication is going to be way slower than a simple query of a high performance clock.
Now, steady_clock::now() might be too slow in the loop.
Using OS specific APIs, bind your thread to have ridiculous priority and affinity for a specific CPU. Or use rdtsc, after taking into account everything that can go wrong. Calculate what value you'd expect to get if (a) something went wrong, or (b) you have passed the time threshold.
When that happens, check steady_clock::now(), see if you are close enough to being done, and if so finish. If not, calculate a new high performance clock target and loop again.
What does it mean for a function call to "spin?" Is it the same as blocking?
This is the context I'm referring to:
/*
* Obtain a free channel
* This call spins till a free channel is obtained
*/
chNum = _getFreeChannel(&tccNum);
Thanks.
To loop, basically. What a spinning function does is busy-waiting with a loop.
A spin is a concurrency technique. Essentially the function loops until the desired condition is met.
It can be computationally expensive if the spin time is large, but can be preferable to wait and notification idioms (for which there is a set-up overhead) if the expected spin time is very small with low variance.
When a Function spins, it is typically checking some condition (like a variable) over and over in a tight loop until it becomes some interesting value. It then continues running once the condition is met.
I would like to have several threads which change the value of certain elements periodically. Let's say I have some kind of run-method changing the value and a certain amount in milliseconds of sleep afterwards. I do need to be able to change the interval a) right after the change and b) after the sleep. I also need a possibility to change between single execution and repeated execution in timed intervals.
The problem with using a Timer is, that I do not have the possibilities I have with using threads directly, like naming or using conditions.
Can anybody please give me a hint in the right direction?
This is what I need to do -
1. Define a handle threadHandle and define an array of handles h[20]...where each entry in the array has value threadHandle.
My code opens up 20 threads and once done, each thread has to signal the main thread and once all of them signal, the main thread has to log something to a log file.
I plan to do something like:
define threadHandle and the array of handles h[20} defined above.
Obnce the code opens 20 threads, do - waitformultipleobjects(NULL,20,h,true,10000)
Now the code will wait for the all the handles in the h array to be set before the wait returns. But since all the values of h are the same, the wait function returns an error. Is there a way to go around this? I basically need all the threads to signal back to the calling thread...defining 20 handlers for each of the 20 threads doesnt seem to be a good idea either.
Can I do something like this instead? -
define threadHandle and the array of handles h[20].
Maintain a variable count for the number of threads that signaled back to the main thread.
waitforsingleobject(threadHandle)
once this returns, increment count and if count < 20 repeat the above wait statement.
Keep doing it till count = 20 and then log to file.
Of course, in between if any of the waits timesout, then we log a failure to the log file.
I am trying this out, but was wondering if there is a better way to do this.
TIA.
anand
Create 20 Event objects. Put their handles into h. Pass one to each thread you create. When the thread needs to signal the parent, it signals that event. The parent waits on the Event handles, and when they're all signaled, it writes to the log.
Use one semaphore instead, (See CreateSemaphore() API, count initialized to 0), that all the threads signal. WaitForSingleObject in a for loop, counting up to 20. Much easier to set up, cannot miss any events and will work for any number of threads, (within reason).
Maintain a variable count for the number of threads. Yes you can do that.
nCount The number of object handles in the array pointed to by lpHandles. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS. This parameter cannot be zero.
nCount is not specifying the array size but the number of handles to wait for. However, it shall not exceed the array size and both shall not exceed MAXIMUM_WAIT_OBJECTS.
Hint: This is not limited to specific handles like thread handles. You can handle a mixture of various waitable handles this way. (MSDN WaitForMultipleObjects function)
But since all the values of h are the same... No, they are not the same and the return value of WaitForMultipleObjects will vary accordingly (WAIT_OBJECT_0 + nCount).
This must be an easy question but I can't find a properly answer to it.
I'm coding on VS-C++. I've a custom class 'Person' with attribute 'height'. I want to call class method Grow() that starts a timer that will increment 'height' attribute every 0.5 seconds.
I'll have a StopGrow() that stops the timer and Shrink() that decrements instead of increment.
I really need a little push on which timer to use and how to use it within Grow() method. Other methods must be straight forward after knowing that.
That's my first question here so please be kind (and warn me if I'm doing it wrong :) Forgive my English, not my first language.
Do you really need to call the code every half second to recalculate a value? For most scenarios, there is another much simpler, faster, effective way.
Don't expose a height member, but use a method such as GetHeight(), which will calculate the height at the exact moment you need it.
Your Grow() method would set a base height value and start time and nothing else. Then, your GetHeight() method would subtract the starting time from the current time to calculate the height "right now", when you need it.
No timers needed!
Since you're on Windows, the simplest solution is probably to use the GetTickCount() function supplied by Windows.
There isn't a good timer function in the C++ language with a precision guaranteed to be less than a second.
So instead, include the windows.h header, and then call GetTickCount() to get a number of milliseconds. The next time you call it, you simlpy subtract the two values, and if the result is over 500, half a second has elapsed.
Alternatively, if you want to block the thread for half a second, use the Sleep(n) function, where n is the number of milliseconds you want the thread to sleep. (500 in your case)
You might want to take a look at CreateTimerQueue() and CreateTimerQueueTimer(). I've never personally used them, but they would probably fit the bill.
I currently spawn a thread that is responsible for doing timer based operations. It calls WaitForSingleObject() on a manual-reset event with a 10ms timeout. It keeps an internal collection of callbacks in the form of pointer-to-method and objects that the callbacks are invoked for. This is all hidden behind a singleton that provides a scheduler interface that let's the caller schedule method calls on the objects either after a timer expiration or regularly on an interval. It looks like the two functions that I mentioned should give you pretty much the same functionality... hmmm... might be time to revisit that scheduler code... ;-)
Sleep() an the normal timer event run off a 10ms clock.
For high resolution timer events on windows use high resolution timers
Not an easy question at all! You have at least two possibilities:
create a thread that will execute a loop: sleep 0.5s, increase height, sleep 0.5s, increase height, etc.
invert flow of control and pass it to some framework like Boost::Asio that will call your timer handler in every 0.5s.
In order to make the right decision you have to think about your whole application. Does it compute something (then maybe threads)? Does it interact with the user (then maybe event driven)? Each approach has some gotchas:
When you use threads you have to deal with locking, which can be tricky.
When you do event-driven stuff, you have to write asynchronous handlers, which can be tricky.