|
Before digging deep into the hows and whys, read this[^] regarding windows and timing.
Afterwards, have a look at multimedia timers (timeBeginPeriod, timeSetEvent and so on).
The use of multimedia timers will give you the best performance considering windows not being a real-time OS.
BTW, boosting both the thread's and the process' priority to "realtime" will prevent even task manager from running as expected.
Hope this helps
--
Roger
It's supposed to be hard, otherwise anybody could do it!
|
|
|
|
|
First, the article referred to by Roger is out of date and contains some errors [this was edited to make it more clear that I was talking about the article Roger linked to and that I am not saying the article is full of errors. It is not.] Most importantly, a thread does not have to run for it's entire quanta (or time slice) and in reality, most do surrender most of it. Second, W2K and XP use a different resolution on timers [Edit: this is misleading. I meant to say that W2K and XP are different than NT, not necessarily from each other. W2K, for example, allows much more flexibility over the quantum table: One significant change to W2K
http://www.sysinternals.com/Information/Windows2000Quantums.html[^]]
The article is [very] right that that Windows is NOT a real time OS. It cannot guarantee that a thread will execute at a set time unless you add specialized hardware and drivers. However, it generally responds within 1ms of your ideal--even WM_TIMER is pretty accurate if you're talking 50ms. [I stand by this; note the phrase "in general."]
Take a look at SetWaitableTimer for one option.
Another is to use WaitForSingleObject and use a timeout that you calculate using GetTickCount() [Edit: QueryPerformanceTimer() is a better choice] with each loop based on how much time the operation of the loop took. I've used this for applications where I needed behavior like SetWaitableTimer() but was severely limited on the number of handles I could use.
Anyone who thinks he has a better idea of what's good for people than people do is a swine.
- P.J. O'Rourke
-- modified at 12:20 Wednesday 26th October, 2005
|
|
|
|
|
Joe Woodbury wrote: the article referred to by Roger is out of date and makes several errors
If this is so, please provide some links to MSDN or similar. Otherwise this is just an opinion which I disagree with and my opinion is based on my own experience on various windows OS versions.
Joe Woodbury wrote: a thread does not have to run for it's entire quanta
True. But this is not done by the OS scheduler. It requires the thread to call either ::Sleep(0) or one of the ::WaitForXXXObject functions.
For the thread to relinquish its time slice by calling ::Sleep(0) requires that there is another thread of equal or higher priority that is ready to run, otherwise the thread is resumed.
This is not a matter of opinion, you can read about it in MSDN[^].
Joe Woodbury wrote: W2K and XP use a different resolution on timers
What timers? Is this another opionion or do you have links?
As an example I've tried the same code running on WinNT4 and WinXP with a better result regarding response time on an older P2 machine running WinNT4 than a fairly new P4 running WinXP using waitable timers.
Regardless of how I designed my executable this would not be the case if what you claim was the fact.
Joe Woodbury wrote: it generally responds within 1ms of your ideal
This I have never experienced on any version of windows without the use of multimedia timers.
How have you measured this?
Joe Woodbury wrote: even WM_TIMER is pretty accurate if you're talking 50ms
Do you really think he meant ±50ms when he has boosted both the priority of the process and the thread to "realtime"?
I get the impression that he want a timer event to occur every 50ms with the highest precision available.
To even mention WM_TIMER in such case is absurd since WM_TIMER is a low priority message and will only be generated if there are no other messages in the thread's message queue. This means that moving the mouse around above your window could delay the WM_TIMER message to be generated/handled.
Again this can be read in MSDN[^].
To use ::WaitForSingleObject to wait for a waitable timer could be a solution.
When the timer event is signalled, the waiting threads priority is boosted by 1 to make the scheduler run the waiting thread ASAP.
A better alternativ than ::GetTickCount() regarding measuring time is the use of ::QueryPerformanceCounter().
Don't make the mistake assuming that something has the same precision as the least significant bit of the value, i.e. ::Sleep(1) does not necessarily generate a delay of one millisecond.
--
Roger
It's supposed to be hard, otherwise anybody could do it!
|
|
|
|
|
(Failing to learn lessons from the past, I wrote my original reply at 3:00 in the morning. I have taken the liberty to totally edit this. I belately realized I did not make several things clear including that I was referring to the article Roger referenced, not the comment Roger made.)
First, I did not mean to imply the article Roger referenced is horribly wrong. It is out of date; it was written five years ago and ends with NT 4 Alpha information which I think may be incorrect--I believe NT 4 still uses 10 ms resolution.) Since then Windows XP, Windows Server 2003 and several iterations of Windows CE have been released. Windows CE 5.0 is most definitely an RTOS. (W2K has much more flexibilty in controlling quantum lengths as outlined in this article: http://www.sysinternals.com/Information/Windows2000Quantums.html[^].)
The article does contain some innacuracies. For example, thread quanta are determined by clock ticks, not by a set time. The HAL determines clock ticks. The author implies this, but doesn't state it clearly.
Second, I did not make it clear in my original posting that I had made the tacit assumption we were talking about the predictability of a 50ms timer as stated in the original question.
Third, my response was dealing with typical behavior, which in Windows is all you can really do. In practice, Windows threads rarely use their entire quanta. This means that various solutions are possible depending on how much "slop" you want in your system.
In connection with this, the Windows message queue is rarely full of high priority messages (I have a vague recollection of a undocumented caveat to the WM_TIMER documentation, though I may be mistaken.)
Fourth, Roger asked if I "really think he meant ±50ms when he has boosted both the priority of the process and the thread to "realtime"?"
I did not say anything about ±50ms; again I assumed, perhaps erroneously, that the original poster wanted some code to execute every 50ms. Since Windows is not an RTOS, a Windows programmer must accept that in the best case, you must accept a tolerance of at least +1ms. Also, THREAD_PRIORITY_TIME_CRITICAL threads in REALTIME_PRIORITY_CLASS processes are a really bad idea, and rarely needed, unless you know exactly what you are doing. I attempted to find information on thread inversion behavior, if any, with this situation and could not.
A good article on this: http://www.microsoft.com/mspress/books/sampchap/4354c.asp[^]
Once you accept that there will be some inaccuracy, the only question is how much is tolerable. (In my own experience working on both hard and soft RTOS systems, this unpredictability is very often the bigger problem.) WIth this in mind, a much wider range of solutions are possible. (QueryPerformanceCounter() is a better solution than GetTickCount(), though the latter will, again, work depending on your criteria.)
It is my experience is that developers new to multi-threading, myself included, often start playing with thread priority thinking that will solve problems that are ultimately problems with design. I think that is the case here; he is forgetting the time used by the task and is thus simply adding a 50ms delay between task execution, not doing something roughly every 50ms.
Finally, I have measured timings by comparing internal x86 counters against the timing of threads as well as using QueryPerformanceCounter().
-- modified at 12:20 Wednesday 26th October, 2005
|
|
|
|
|
Hi everyone,
I need some help with a design problem that I have. I am not exactly a software developer by profession, so I am hoping to get some suggestion from the experts here.
Well, basically I have 2 types of tracking systems (optical and sonar). So, basically I have an interface object and they both should inherit from it.
However, my problem is that they both take different parameters for initialization. So, if I have a method calloed Initialize, I cannot share it between then as they take different parameters for initializazion.
I was wondering what kind of design patterns you guys would recommend for developing objects that are of course same from a functional point of you, but differ internally quite substantially.
Thanks and cheers,
Keith
|
|
|
|
|
Hi,
do users set the parameters needed for initialization at runtime ?
We can do no great things, only small things with great love. - Mother Theresa
|
|
|
|
|
Normaly initialization only needs to be done when the object if first created, at which point in time you already know what type it is. Given that, use an abstract base class that only provides the interfaces they have in common and provide each derived class with an initialization function specific for that class. Do not make the initialization function part of the base class, because it only provides the interface that you need to access after initialization.
If for some reason you need to reinitialize the object thru a pointer to the base class (unusual). You'll need to know what all the derive classes are so you can use dynamic_cast<>() to downcast the base class pointer to one of the derived types. At which time you will know what type it is and what paramenters are required.
INTP
Every thing is relative...
|
|
|
|
|
|
This is quite common; the derived objects have their own constructors. They each can call the base constructor (or Init() function) with those parameters that are in common.
If the object has to be created early and then fully initialized later, you can create two virtual functions in the base object, one for each type. Yes, it's ugly, but I've done worse.
Anyone who thinks he has a better idea of what's good for people than people do is a swine.
- P.J. O'Rourke
|
|
|
|
|
Create parameter classes derived from a common base.
something like this
class TrackingParams
{
...
}
class OpticalTrackingParams : public TrackingParams
{
...
}
class SonarTrackingParams : public TrackingParams
{
...
}
class TrackingInterface
{
public:
virtual void Init(TrackingParams &);
};
class OpticalTracking : public TrackingInterface
{
void Init(TrackingParams & params)
{
OpticalTrackingParams & p = dynamic_cast<opticaltrackingparams &="">(params);
}
}
|
|
|
|
|
Im having a little trouble using free after a malloc.
Here is the malloc part:
GUIQueue* newMsg = (GUIQueue*)malloc( sizeof(GUIQueue) );
newMsg->data = (char*)malloc( sizeof(msg.u.reqvid) );
...
GUIQ.push( newMsg );
What i do now is pull the info from the queue (this is a MT'ed app.) and get the info and free the pointer.
GUIQueue* newMsg;
newMsg = (GUIQueue*)GUIQ.front();
GUIQ.pop(); // I know this looks weird, but pop doesnt return anything, so...
...
if( newMsg->data != NULL )
{
free(newMsg->data); // This first free causes the runtime error.
newMsg->data = NULL;
}
if( newMsg != NULL )
{
free(newMsg);
newMsg = NULL;
}
The error message that pops up is:
Unhandled exception at 0x7c901230 in LiteCycles.exe: User breakpoint.
I've cleared all my breakpoints, so i dont think it can be that, the stack looks like its deep in free and the last legiable method is _CrtIsValidHeapPointer.
Any ideas on whats causing this error? Any input is greatly appricated, thanks.
-Jader89
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
You are using either a class or a template that is called "GUIQueue".
Never mix C++ objects with malloc/free. Use new/delete instead.
Why? Because the object's constructor and destructor won't get called when you are using malloc and free.
What kind of errors you get depend on the C++ object you are using.
--
Roger
It's supposed to be hard, otherwise anybody could do it!
|
|
|
|
|
I tried switching to delete and new, but down the line of delete it still runs into the same method that free does, and cause the same error. Upon review of the last method, in the method header info, it says that it checks to see if the pointer is in the local heap, which i dont think it is in the local heap, cause its a different thread thats creating it, so this could be the main problem.
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
I'm not really familiar with multithreaded application, but I think you will need to block the
access to your data when you free it; it looks like one of your thread will try to access the data while your are free-ing it.
have a look at mutex, critical section, and all the other related mechanism for locking access to your data to only one thread.
Maximilien Lincourt
Your Head A Splode - Strong Bad
|
|
|
|
|
I think I see what your saying, but the only thing that accesses the data after its created, is the same thread that free()'s it. So its not something else trying to access the data. Is that what you were getting at?
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Jader89 wrote: newMsg->data = (char*)malloc( sizeof(msg.u.reqvid) );
Note the value of newMsg->data after this point.
Jader89 wrote: free(newMsg->data);
Note the value of newMsg->data before this point. Is it the same as it was after the call to malloc() ? If not, that's why free() is failing.
|
|
|
|
|
The pointer is a valid one, and the same as it is when its created.
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Can you confirm that this works:
class GUIQueue
{
public:
char *data;
};
void main( void )
{
GUIQueue *newMsg = (GUIQueue *) malloc(sizeof(GUIQueue));
newMsg->data = (char *) malloc(15 * sizeof(char));
if (newMsg->data != NULL)
{
free(newMsg->data);
newMsg->data = NULL;
}
if (newMsg != NULL)
{
free(newMsg);
newMsg = NULL;
}
}
"Take only what you need and leave the land as you found it." - Native American Proverb
|
|
|
|
|
I'll try this out. As a side note, the free(newMsg) works fine... Its just the char* thats in the struct GUIQueue that doesnt seem to want to free... Ill reply soon on the results.
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Yup, this segment of code works fine...
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Then some other piece of code is changing newMsg->data before free() is called. Either take away from your current program, or add to this temporary program, until you find the offending statement(s).
"Take only what you need and leave the land as you found it." - Native American Proverb
|
|
|
|
|
Well it seems the mix up occurs somewhere between pushing the it on the queue, and taking it off. I tried just a push followed by a pop, and i run into the problem. Any ideas why?
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Jader89 wrote: Any ideas why?
Not without seeing the code for the 'push' and 'pop' operations.
"Take only what you need and leave the land as you found it." - Native American Proverb
|
|
|
|
|
The queue:
std::queue<GUIQueue*> GUIQ;
the struct:
struct GUIQueue<br />
{<br />
bool isBmp;<br />
int size;<br />
char* data;<br />
};
other than that, i just imported the queue.h header file,
and used the methods push(), and front(), since pop doesnt really do anything
other than completely remove the front of the queue.
here is the failing code as one thread, also note, that without the push, and pop, the free()'s worked fine.:
GUIQueue* newMsg = (GUIQueue*)malloc( sizeof(GUIQueue) );<br />
memset( newMsg, 0, sizeof(GUIQueue) );<br />
newMsg->data = (char*)malloc( sizeof(msg.u.reqvid) );<br />
memcpy( newMsg->data, &msg, sizeof(msg.u.reqvid) + sizeof( MsgHeader ) );<br />
newMsg->size = sizeof(msg.u.reqvid) + sizeof(MsgHeader);<br />
newMsg->isBmp = true;<br />
GUIQ.push( newMsg );<br />
<br />
GUIQueue* test = (GUIQueue*)GUIQ.front();<br />
GUIQ.pop();<br />
if( test->data != NULL )<br />
{<br />
free(test->data);<br />
test->data = NULL;<br />
}<br />
if( test != NULL )<br />
{<br />
free(test);<br />
test = NULL;<br />
}
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|
Correction:
If i keep the same pointer name, newMsg, and call free on that, it will work for both ->data, and on itself. But if i switch pointers names ,( i.e. GUIQueue* test = newMsg ), then call do the same free()'s but on test, it fails.
"There are 10 types of people, those who understand binary, and those who don't."
- Somebody, not me.
|
|
|
|
|