Yet another timers-and-threads question

I've got a requirement to be able to set a timer and be told when it
expires, eg by a callback.

SetTimer with WM_TIMER is not generally useful, as you have to have a
window, and some of the threads in which I want to do this don't have
windows.

SetTimer with callback function is not generally useful, as it's not
sufficient that there's a message pump somewhere in the *application*, there
has to be a message pump in the *thread* that calls SetTimer (well
documented, that, not), and some of the threads in which I want to do this
don't have message pumps.

CreateWaitableTimer looks interesting, but in practice doesn't work as it
requires that every wait everywhere in the calling thread is an "alertable"
wait, which means, for example, finding all the calls to
WSAWaitForMultipleEvents hidden in DLLs for which you don't have the source
code and changing their last parameter to TRUE.

So ... I can hook into an existing window somewhere and get it to process
WM_TIMER, or I can set up a separate thread to do a waitable timer and the
callback, but is it really that complicated?? Is there really no reliable
way I can say "please call me back in a couple of seconds" without going to
all that hassle??

Here's the desired model:

(1) There's a little mixin class called Timer which any class (window or
non-window) can inherit from.

(2) The class can then call setTimeout( seconds ) and killTimeout().

(3) When the timer expires the virtual function timeout() is called (I don't
care in which thread, I can synchronise stuff if I have to).

the idea being to add timeouts to objects of any class running in any thread
(ie GUI or non-GUI, which might wait on WaitForMultipleObejcts or recv or
absolutely anything else) in a couple of lines of code.

--
Tim Ward
Brett Ward Limited - www.brettward.co.uk


0
tw2 (223)
4/5/2006 1:01:33 PM
vc.mfc 33608 articles. 0 followers. Follow

5 Replies
622 Views

Similar Articles

[PageSpeed] 13

You could have a worker thread that just does a sleep for the amount of time 
you want to wait and then sets a variable that is accessible from the other 
class when the time is up.  That way you could check the variable (make it a 
volatile) to see if you've run out of time.

Tom

"Tim Ward" <tw2@ipaccess.com> wrote in message 
news:49htdeFodqvpU1@individual.net...
> I've got a requirement to be able to set a timer and be told when it
> expires, eg by a callback.
>
> SetTimer with WM_TIMER is not generally useful, as you have to have a
> window, and some of the threads in which I want to do this don't have
> windows.
>
> SetTimer with callback function is not generally useful, as it's not
> sufficient that there's a message pump somewhere in the *application*, 
> there
> has to be a message pump in the *thread* that calls SetTimer (well
> documented, that, not), and some of the threads in which I want to do this
> don't have message pumps.
>
> CreateWaitableTimer looks interesting, but in practice doesn't work as it
> requires that every wait everywhere in the calling thread is an 
> "alertable"
> wait, which means, for example, finding all the calls to
> WSAWaitForMultipleEvents hidden in DLLs for which you don't have the 
> source
> code and changing their last parameter to TRUE.
>
> So ... I can hook into an existing window somewhere and get it to process
> WM_TIMER, or I can set up a separate thread to do a waitable timer and the
> callback, but is it really that complicated?? Is there really no reliable
> way I can say "please call me back in a couple of seconds" without going 
> to
> all that hassle??
>
> Here's the desired model:
>
> (1) There's a little mixin class called Timer which any class (window or
> non-window) can inherit from.
>
> (2) The class can then call setTimeout( seconds ) and killTimeout().
>
> (3) When the timer expires the virtual function timeout() is called (I 
> don't
> care in which thread, I can synchronise stuff if I have to).
>
> the idea being to add timeouts to objects of any class running in any 
> thread
> (ie GUI or non-GUI, which might wait on WaitForMultipleObejcts or recv or
> absolutely anything else) in a couple of lines of code.
>
> --
> Tim Ward
> Brett Ward Limited - www.brettward.co.uk
>
> 


0
tserface (3860)
4/5/2006 3:00:35 PM
"Tim Ward" <tw2@ipaccess.com> wrote in message 
news:49htdeFodqvpU1@individual.net...
> (snip)
> Here's the desired model:
>
> (1) There's a little mixin class called Timer which any class (window or
> non-window) can inherit from.
>
> (2) The class can then call setTimeout( seconds ) and killTimeout().
>
> (3) When the timer expires the virtual function timeout() is called (I 
> don't
> care in which thread, I can synchronise stuff if I have to).
>
> the idea being to add timeouts to objects of any class running in any 
> thread
> (ie GUI or non-GUI, which might wait on WaitForMultipleObejcts or recv or
> absolutely anything else) in a couple of lines of code.

I think that is a fantastic idea.  The main problem is having a thread that 
is running some function, that can be interrupted.  You have to add special 
code to every function in every thread to know that it can be interrupted by 
a timeout.

If your threads are always waiting, then add a new event that your 
timer-window can signal, and have your thread wait on that event also.  Of 
course, this means that every timer for every thread would need a unique 
event.

If your threads are compute-intensive and never waiting -- I believe you can 
still use the above-mentioned event to signal the function.  You would have 
to make sure the threads computation runs in a tight loop that looks like 
the following:
while (WaitForSingleObject(handleTimeoutEvent, 0) == WAIT_TIMEOUT)
{
// continue computation here
}

Good luck
DanB 


0
Dan
4/5/2006 3:03:56 PM
"Dan Baker" <dbmail> wrote in message
news:OQuIqIMWGHA.1348@TK2MSFTNGP05.phx.gbl...
> "Tim Ward" <tw2@ipaccess.com> wrote in message
> news:49htdeFodqvpU1@individual.net...
> > (snip)
> > Here's the desired model:
> >
> > (1) There's a little mixin class called Timer which any class (window or
> > non-window) can inherit from.
> >
> > (2) The class can then call setTimeout( seconds ) and killTimeout().
> >
> > (3) When the timer expires the virtual function timeout() is called (I
> > don't
> > care in which thread, I can synchronise stuff if I have to).
> >
> > the idea being to add timeouts to objects of any class running in any
> > thread
> > (ie GUI or non-GUI, which might wait on WaitForMultipleObejcts or recv
or
> > absolutely anything else) in a couple of lines of code.
>
> I think that is a fantastic idea.  The main problem is having a thread
that
> is running some function, that can be interrupted.  You have to add
special
> code to every function in every thread to know that it can be interrupted
by
> a timeout.

Well, I've now got two separate versions - one that works in GUI threads,
using SetTimer, and the other that works in threads that do alertable waits
from time to time, using CreateWaitableTimer. In fact ,in the thread in
question that I wanted to add this to, the thread is normally waiting on
WaitForMultipleObjects, and this code was in a module I *did* have the
source for, so I changed it to WaitForMultipleObjectsEx and handled the
extra return code.

Not a general solution, but good enough for me for today.

Next, see if I can make CancelWaitableTimer work properly in this context
....

--
Tim Ward
Brett Ward Limited - www.brettward.co.uk


0
tw2 (223)
4/5/2006 3:14:06 PM
"Tim Ward" <tw2@ipaccess.com> wrote in message 
news:49i55vFo9a8pU1@individual.net...
| "Dan Baker" <dbmail> wrote in message
| news:OQuIqIMWGHA.1348@TK2MSFTNGP05.phx.gbl...
| > "Tim Ward" <tw2@ipaccess.com> wrote in message
| > news:49htdeFodqvpU1@individual.net...
| > > (snip)
| > > Here's the desired model:
| > >
| > > (1) There's a little mixin class called Timer which any class (window 
or
| > > non-window) can inherit from.
| > >
| > > (2) The class can then call setTimeout( seconds ) and killTimeout().
| > >
| > > (3) When the timer expires the virtual function timeout() is called (I
| > > don't
| > > care in which thread, I can synchronise stuff if I have to).
| > >
| > > the idea being to add timeouts to objects of any class running in any
| > > thread
| > > (ie GUI or non-GUI, which might wait on WaitForMultipleObejcts or recv
| or
| > > absolutely anything else) in a couple of lines of code.
| >
| > I think that is a fantastic idea.  The main problem is having a thread
| that
| > is running some function, that can be interrupted.  You have to add
| special
| > code to every function in every thread to know that it can be 
interrupted
| by
| > a timeout.
|
| Well, I've now got two separate versions - one that works in GUI threads,
| using SetTimer, and the other that works in threads that do alertable 
waits
| from time to time, using CreateWaitableTimer. In fact ,in the thread in
| question that I wanted to add this to, the thread is normally waiting on
| WaitForMultipleObjects, and this code was in a module I *did* have the
| source for, so I changed it to WaitForMultipleObjectsEx and handled the
| extra return code.
|
| Not a general solution, but good enough for me for today.
|
| Next, see if I can make CancelWaitableTimer work properly in this context
| ...
|
| --
| Tim Ward
| Brett Ward Limited - www.brettward.co.uk
|

How about a Meyers singleton to track all of your timers?  This would save 
you the trouble of scattered timers all over your code AND give you the 
capability of cancelling any or all of them at will.

-- Ed.

-----------------------------------------------------
"Want fly with that odor?"
- Chinee McDonald

"Want flies with your odor?"
- Japanese McDonald's
-----------------------------------------------------

0
Anon3258 (180)
4/5/2006 3:25:12 PM
hi folks,
i'm using in cases like this multimedia timers, which working well even
in threads without message pump.
see the following code fragment:


TIMECAPS tc;
MMRESULT rc = ::timeGetDevCaps(&tc, sizeof(tc));
ASSERT(rc == TIMERR_NOERROR);
ASSERT(tc.wPeriodMin == 1);	// check for 1 ms resolution

// start timer (cyclic call of function staticTimerProc)
m_tId = ::timeSetEvent(1, 0, staticTimerProc, LPARAM(this),
TIME_PERIODIC);
ASSERT(m_tId != 0);

....

// stop timer
::timeKillEvent(m_tId);


don't forget to link the mmlib.lib (think that was the name) too.

regards,
martin

0
4/5/2006 3:39:21 PM
Reply:

Similar Artilces:

Autoforward Rule Question
We are a large Org, and this particular User waould like top do the following: Outlook 2003/Exchange 2000 When this User gets mail, the User would like to use a rule to Autoforward the mail item to another mailbox BUT with format change to always be HTML. Is that possible?. -- Amin M. not using rules - you'd need to write VBA to do it. -- Diane Poremsky [MVP - Outlook] Author, Teach Yourself Outlook 2003 in 24 Hours Coauthor, OneNote 2003 for Windows (Visual QuickStart Guide) Author, Google and Other Search Engines (Visual QuickStart Guide) Outlook Tips: http://www.outlook-tips.net/...

yet another sending error
Good day all I am not able to send mail but can receive them. I was using norton and uninstalled it to no avail. I tried different connections( wi fi. and 2 different dial ups) I also used the telnet tool but I get an error and i even formatted my pc... no luck. I tried 2 email addys with no success ( The connection to the server has failed. Subject '', Account: 'pop.gmail.com', Server: 'smtp.gmail.com', Protocol: SMTP, Port: 465, Secure(SSL): Yes, Socket Error: 10060, Error Number: 0x800CCC0E) Norton products when uninstalled leave a lot of proble...

BE question
I am constantly asked to make slight changes in forms while developing. I rolled out a new form and the users want this moved and that moved or one little slight adjustment here and there or a new field added. My problem is, I can't add a new field in a BE linked table while the users are in it. I either have to catch my BE early in the morning before users get on or late in the afternoon after they are gone. Is there any way to force a save of the BE while users are in it? Thanks so much!!!! -- Milton Purdy ACCESS State of Arkansas No, and you'd probably corrupt th...

questions about Active Document. thank you.
hi, here i am building an Active Document Server, and get some problems. i have a control bar and a list control in the frames(CMainFrame and CIPlaceFrame). when display a image file,i want to list all the supported files under the same folder in the list control. but when my program is embeded in IE,the list control can't add in any string,and everything is ok when the program runs stand alone yet. in the Doc file, after OnOpenDocument(),i get a pointer to the CInPlaceFrame,and then call its member function LoadFileList(...) to load the file name list. i use a lot of AfxMessageBox(......

Another NameTable Question
I am trying to work out the best way to use the NameTable class in my C# application. I am assuming that getting/adding a string to the nametable has the same overheads as comparing a string normally, so I have created a class which holds references to the atomized strings. Is there a better way to do this? simple example below //Class to provide "string constants" private class MyStrings { public String stringA; public String stringB; public MyStrings(NameTable nt) { stringA = nt.Add("A"); stringB = nt.Add("B"); } } //Class...

filtered list question
I want to autofilter a list and then run a vlookup based on the criteria used. How do you reference the first cell of a filtered list? Assumptions: A2:C10 contains your data E1 contains your lookup value You wish to return the corresponding value in Column C Formula: =VLOOKUP(E1,IF(SUBTOTAL(3,OFFSET(A2:A10,ROW(A2:A10)-MIN(ROW(A2:A10)),0,1) ),A2:C10),3,0) ....confirmed with CONTROL+SHIFT+ENTER, not just ENTER. Adjust the formula accordingly. Hope this helps! In article <B218E24D-73A1-4BCE-8B8A-2A52DD6074BE@microsoft.com>, "Bob B" <Bob B@discussions.microsoft.com...

Question about using the right or left formula
How do you get excel to recognize the data as a number when using the right or left formula? For example, cell L73 has the following formula: =RIGHT(D3,5) The data this equation produces is +137. I have another cell that has a formula that says =IF(ISNUMBER(L73),L73,"NO"). The answer I get is NO. I should get +173. I have formatted cell L73 to be a number. How do I fix this formula? Thanks Being a text function, the right function will return text. To cause Excel to perform an implicit type change from text to numeric try one of these: =--RIGHT(D3,5) =RIGHT(D3,5)*1 D...

MAD Monitoring thread starting sporadically
Hi, My server is delivering mail fine, but I am getting repeated instances of Event IDs 9095 and 9096 (see below). The explanation from MS says: Explanation This occurs when Exchange System Attendant service is started and whenever configuration changes are made that could affect the monitoring work of Exchange System Attendant. User Action No user action is required. If this event occurs frequently, contact Microsoft Product Support Services. My question is, how often is "frequently"? I am seeing this at least a couple times a day when I am not manually stopping and start...

CImageList and CImage question
I want to use an image list with a list control. I am using CImage to load a bitmap file (actually several files) like: CImage image; image.Load("test.bmp"); How do I add this image to a CImageList, which can then be used by the list control? -- Regards, Frank This looks ugly but seems to be the only way. CImage image; image.Load("test.bmp"); CBitmap Bmp; Bmp.Attach(image.Detach(); m_ImageList.Add(&Bmp,RGB(0,0,0)); Bmp.DestroyObject(); image.Load("test2.bmp"); Bmp.Attach(image.Detach(); m_ImageList.Add(&Bmp,RGB(0,0,0)); Bmp.DestroyObject(); .... ...

How do I copy a formula from one worksheet to another?
I have a formula in one worksheet and want to copy that result to a cell in another worksheet. When I try to do that, I get "#REF#" in the destination cell. How can I make this work? "cahduq" <cahduq@discussions.microsoft.com> wrote in message news:B6A6EE7C-B925-4FCE-B2EE-D8F8D6B601D3@microsoft.com... >I have a formula in one worksheet and want to copy that result to a cell in > another worksheet. When I try to do that, I get "#REF#" in the > destination > cell. How can I make this work? > Copy-Paste Special-Values Hi If you on...

having one field display when another field changes
I have a field CHSTAT that updates in the original database I want a new field that will display something different as the CHSTAT updates and changes ie. CHSTAT = "10" new field = "Printed"......CHSTAT = 20 new field= "Located" Cheers!! In tables and fields you should have a table that has a field that has the CHSTAT values and a field that has the equivalent text values. Then you join that table to the current table in a query on the CHSTAT values. If you want to do this on a form, you could use a combobox to select the values. The source ...

Migrating GP to another Existing Server
Hi, So far I can only managed to find documentation on GP migration to a new server. Is there any documentation on migration to another existing GP Server? We currently have two different MGP systems (1 in the UK and 1 in Singapore) and plan to consolidate them in Singapore. Any help would be appreciated! Cheers, Sugih If you are going to add the UK db to the Singapore server in ONE GP install with 2 companies: 1. Backup the UK company using the SQL backup tool. Take the file to Singapore. 2. On the Singapore GP install, create a new company. Use the same name as the UK compan...

Excel Font question: Can you overscore a character?
I would like to overscore a character within a cell in an Excell spreadsheet. I am able to add a Equation box with an overscore (insert object, microsoft equation 3.0, overbar template), but this only seems to work in a floating text box. I would like to type in crystollography references -- for instance, inside a cell <"one one onebar"> as <111> with a bar over the third one. Is there any way to type <111> with a bar over the third one in a cell in Excel? Thanks, Joe It looks like my question posted twice. Please ignore this posting. "DrJoe" wr...

Moving Mailboxest another user
We use Windows 2000 Server, with Exchange 2000 using outlook. I want to be able to move the Outlook information from the mailboxes, calendars and address books from one user to another user so that I can delete the original user but not lose the information. How can I do this? Ok If the new user not have data in his mailbox the operation is very simple.. 1. Delete new user mailbox (from AD Users & Computers) 2. Delete old user mailbox (from AD Users & Computers) 3. Open Exchange System Manager navigate to server ->mailbox store -> mailboxes Right click -> run cleanu...

Curious Database Query Question
When creating a "New Database Query" from another Excel workbook, when you get to the "Select Workbook" dialog, there is a small checkbox labelled "Read Only". According to the help file, it has this to say: "To prohibit updates to this file, select the Read Only check box." I don't understand why this is an issue. In my understanding, database query is a one-way transfer of data from the external source to your excel workbook...if you edit the data in your workbook, that *doesn't* change the data back in the external source...right? Am I wr...

SOP process question
Hi, We use SOP and have a new process that I'm not sure how to handle. We receive an order from a customer for a year's worth of product. We need to book the order to show a quantity of 12 but bill and fulfill 1 item monthly. Is there any automated way to fill the order monthly (decrement the inventory by 1 every month) and invoice without having to go in to every order? I looked at using recurring orders but that does not give us the line item with a quantity of 12 for reporting....I feel like I'm missing something very basic. Thank you! Yes and no.... ...

single instance YET ...
Hi, I wish to have my MDI based MFC application to be single instance. Let's assume I use the unique class name method. When my application starts, I check to see if there's already an instance running. If so, I set focus to active instance and terminate. But now I wish this: When a second instance is started with command line parameters, I wish to terminate that instance, but pass the command line parameters to the first instance (a file name, so that it can be openend as another document inside my MDI application). How do I pass this info? Is it possible to pass this via a window...

Extract data on one spreadsheet to another based on criteria
I have a list of data on one worksheet called raw_data coming from an external HR database example below: Month Site Hire Date Name Employee ID January Bedfont 01/01/2007 Andrew 000000001 January Bedfont 05/01/2007 Harry 000000002 January Hams Hall 31/01/2007 Simon 000000003 January Colworth 31/01/2007 Jenner 000000004 January Colworth 31/01/2007 Harry 000000005 February Leeds 09/02/2007 Simon 000000006 February Colworth 10/02/2007 Mavis 000000007 February Colworth 11/02/2007 Harry 000000008 February Hams Hall 12/02/2007 Jenn...

Load event question
I found this code along with it's function on this discussion group. It works great but I want it to populate the text field when the form loads. How can I get the following code on the Form_Load()? fOSUserName() is a defined function. Private Sub Form_BeforeUpdate(Cancel As Integer) On Error GoTo BeforeUpdate_Err ' Set bound controls to system date and time and current user name Me.DateModified = Now() Me.ModifiedBy = fOSUserName() BeforeUpdate_End: Exit Sub BeforeUpdate_Err: MsgBox Err.Description, vbCritical & vbOKOnly, _ &quo...

Referencing Cells in Another Worksheet
I have a worksheet with contact names and numbers and some have a combination of both. I have a Landscape and a Portrait Version. I want to be able to make changes in only one and the other would automatically update. It worked when I first created it using "=", but for some reason, when I inserted some lines and deleted others, the cells stopped working. I tried to fix, but no luck. I've also tried changing both formats to General and number and neither worked. Please help.... thank you! ...

workbook will calculate on one PC but not another
Using xl2002, I created a workbook. it contains a circular reference. i created a workbook_open procedure that appears to have eliminated the problem on my PC... Application.MaxChange = 0.001 ActiveWorkbook.PrecisionAsDisplayed. when i open the workbook on my pc it opens right up, and works. on other PCs, a message appears... "Microsoft Excel cannot calculate a formula. Cell references in the formula refer to the formula's result, creating a circular reference......." Why does the workbook work fine on my PC, and not on others? What can I do to make it work universally? Than...

Update KB 977165 is it safe yet?
I have had updates turned off since the news of the buggy BSOD causing update on Feb 9. Has MS fixed this yet? regards -- Craig News wrote: > I have had updates turned off since the news of the buggy BSOD causing > update on Feb 9. Has MS fixed this yet? The 'problem' - AFAIK anyway - turned out to be infected/infested machines. If your machine is not infested/infected, in particular with: Win32/Alureon.A http://www.microsoft.com/security/portal/Threat/Encyclopedia/Entry.aspx?Name=Virus%3AWin32%2FAlureon.A More information on the ongoing i...

Copying the Editing in one file to Another opened XLS file
hi! I have been given a task to develop some plugin for excel that will copy any type of editing in the current excel file to the other opened excel file. Is it possible. If so then please guide me how to achieve it. Thanks in advance. Ahmad Jalil Qarshi Depends on what you mean by editing - Workbooks("sourcebooks.xls).Worksheets(1).cells.copy ' then pick your poision: Workbooks("Otherbook.xls").Worksheets(1).Cells.PasteSpecial xlFormats Workbooks("Otherbook.xls").Worksheets(1).Cells.PasteSpecial xlValues Workbooks("Otherbook.xls").Worksheets(1).Ce...

What is the Orb? And other new outlook questions
I just reinstalled Outlook (same version (2003) that I was previously using), and there is some behavior that is new that I don't understand. First, when I look at (read) a message, there is an "orb" (ball) to the left of the address in the "From" line, if I put the mouse on it I am shown some information about the sender (including his online/offline status). Where did this come from, can I turn it off. Also, I now have a line at the top of the header area showing me the "zone" of the message ("You are now looking at this message in the internet...

Windows Thread priority
Hello, I tried a quick test on windows threads and have a question about priorities. I made a Dialog app, and a class CMyThread : public CWinThread. I added a ListCtrl to the dialog and then, in the OnIdle function of MyThread, call the function InsertItem of the ListCtrl (using GetDlgItem). When I call ::AfxBeginThread(RUNTIME_CLASS(CMyThread)); it works (the list is quickly populated), but the main dialog doesn't seem to receive any message. The thread seems to take all the process time. When I call ::AfxBeginThread(RUNTIME_CLASS(CMyThread), THREAD_PRIORITY_BELOW_NORMAL); it works fi...