threads won't close and then reopen correctly...

I have a MFC VC++ project that has a thread started in the
OnInitDialog() function of a dialog box.
AfxBeginThread(ThreadProcess, (LPVOID) this, 0);

I handle the thread in the the following function
UINT Questions::ThreadProcess(LPVOID param)
{
   //do some stuff
  AfxEndThread(0);
  return 0;
}

Everything works well until I close the dialog box and then reopen
it.  When I do that the thread doesn't work as it should the second
time around.  Anyone have any thoughts on why I am getting this
unwanted behavior and what I can do to correct it?

Thanks in advance,
RABMissouri2008
0
9/22/2008 8:45:03 PM
vc.mfc 33608 articles. 0 followers. Follow

9 Replies
502 Views

Similar Articles

[PageSpeed] 6

"RAB" <rabmissouri@yahoo.com> wrote in message 
news:c5483a5c-388b-45e6-83fa-a5381a54f50d@m45g2000hsb.googlegroups.com...
> I have a MFC VC++ project that has a thread started in the
> OnInitDialog() function of a dialog box.
> AfxBeginThread(ThreadProcess, (LPVOID) this, 0);
>
> I handle the thread in the the following function
> UINT Questions::ThreadProcess(LPVOID param)
> {
>   //do some stuff
>  AfxEndThread(0);
>  return 0;
> }
>
> Everything works well until I close the dialog box and then reopen
> it.  When I do that the thread doesn't work as it should the second
> time around.  Anyone have any thoughts on why I am getting this
> unwanted behavior and what I can do to correct it?


Does your "//do some stuff" section use the passed parameter after the 
dialog is destroyed?  That could be bad.

Otherwise there's nothing I can see in the code shown that should be  a 
problem.  The debugger should help :)

Mark

-- 
Mark Salsbery
Microsoft MVP - Visual C++


>
> Thanks in advance,
> RABMissouri2008 

0
Mark
9/22/2008 8:52:29 PM
"RAB" <rabmissouri@yahoo.com> wrote in message 
news:c5483a5c-388b-45e6-83fa-a5381a54f50d@m45g2000hsb.googlegroups.com...
>I have a MFC VC++ project that has a thread started in the
> OnInitDialog() function of a dialog box.
> AfxBeginThread(ThreadProcess, (LPVOID) this, 0);
>
> I handle the thread in the the following function
> UINT Questions::ThreadProcess(LPVOID param)
> {
>   //do some stuff
>  AfxEndThread(0);
>  return 0;
> }
>
> Everything works well until I close the dialog box and then reopen
> it.  When I do that the thread doesn't work as it should the second
> time around.  Anyone have any thoughts on why I am getting this
> unwanted behavior and what I can do to correct it?


You haven't described anything about how it fails, but...Try removing the 
AfxEndThread() call.  It is not necessary and it can be harmful.  (With that 
call present, any stack objects created in your thread proc will not be 
destroyed.)

-- 
Scott McPhillips [VC++ MVP] 

0
Scott
9/22/2008 10:55:21 PM
On Mon, 22 Sep 2008 13:45:03 -0700 (PDT), RAB <rabmissouri@yahoo.com>
wrote:

>I have a MFC VC++ project that has a thread started in the
>OnInitDialog() function of a dialog box.
>AfxBeginThread(ThreadProcess, (LPVOID) this, 0);
>
>I handle the thread in the the following function
>UINT Questions::ThreadProcess(LPVOID param)
>{
>   //do some stuff
>  AfxEndThread(0);
>  return 0;
>}
>
>Everything works well until I close the dialog box and then reopen
>it.  When I do that the thread doesn't work as it should the second
>time around.  Anyone have any thoughts on why I am getting this
>unwanted behavior and what I can do to correct it?

"Doesn't work as it should" == "unwanted behavior", and neither tells me
anything specific that would help me help you. I will guess that there
should be only one instance of this thread active at a time, and you're
doing nothing to enforce this. In general, you should join with secondary
threads at some point, and it doesn't appear that you're doing this. For
more on this and other CWinThread issues, see:

http://members.cox.net/doug_web/threads.htm

In addition, calling AfxEndThread() is a bad idea, and it's nonsensical to
write a return statement immediately following it. If MS didn't declare
AfxEndThread __declspec(noreturn), they should have, and then the compiler
wouldn't complain about a missing return statement. But it would still be a
bad idea to call AfxEndThread(), because a return statement is all you need
inside the thread controlling function, and returning normally ensures
local variables are properly destroyed. If for some reason I needed to end
a thread in some deeply nested function call, I would probably throw an
exception of a type that only the thread controlling function will ever
catch. This means always rethrowing from catch(...).

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
9/22/2008 11:58:43 PM
Thanks.  Your responses helped me realize the thread was probably
behaving like it should.  I then found my dumb mistake.  I was using a
boolean variable in OnOK() to check if the dialog box had been
closed.  Within my thread function I constantly had if() statements
checking for this boolean variable and if it was set then exit the
thread.  However, I forgot that I had to set the variable to static or
my project wouldn't build.  As a result, I assumed the variable would
reset itself each time the dialog opened, but because it was static,
it didn't.  There is probably a better and easier way to teminate the
thread when the dialog closes?

Thanks again,
RABMissouri
0
9/23/2008 1:03:18 AM
See below...
On Mon, 22 Sep 2008 13:45:03 -0700 (PDT), RAB <rabmissouri@yahoo.com> wrote:

>I have a MFC VC++ project that has a thread started in the
>OnInitDialog() function of a dialog box.
>AfxBeginThread(ThreadProcess, (LPVOID) this, 0);
>
>I handle the thread in the the following function
>UINT Questions::ThreadProcess(LPVOID param)
>{
>   //do some stuff
>  AfxEndThread(0);
****
Delete the AfxEndThread.  Explicit use of this is always a mistake.  I know the MSDN
documentation shows it being used, and that is a design error which really should be
removed.  
****
>  return 0;
>}
>
>Everything works well until I close the dialog box and then reopen
>it.  When I do that the thread doesn't work as it should the second
>time around.  Anyone have any thoughts on why I am getting this
>unwanted behavior and what I can do to correct it?
****
Note: you MUST make sure that before the dialog box closes, that the thread has
terminated.  In general, a thread should always send a notification to its controlling
window.  See my essay on thread shutdown.  For example,

void CMyDialog::OnOK()
   {
    if(threadrunning)
      {
       closepending = TRUE;
       return;
     }
   ... perhaps other stuff...
  CDialog::OnOK();
  }

LRESULT CMyDialog::OnThreadFinished(WPARAM, LPARAM)
   {
    threadrunning = FALSE;
    if(closepending)
       PostMessage(WM_COMMAND, (WPARAM)IDOK, NULL);
    return 0;
   }

your top-level thread function will be

/* static */ UINT CMyDialog::ThreadProcess(LPVOID p)
   {
    Something * parms = (Something *)p;
    ... do stuff
    p->wnd->PostMessage(UWM_THREAD_FINISHED);
    return 0;
   }

where UWM_THREAD_FINISHED is a user-defined message.  Until you can be sure that the
thread has successfully terminated before the dialog closes, no further discussion of this
problem is possible.  You have no idea what is going on if that thread is still running.
			joe
****
>
>Thanks in advance,
>RABMissouri2008
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
9/23/2008 2:01:25 AM
It should not be a static variable; there is no reason it should be static.  See my essay
on worker threads and how to move from C space to C++ space.
					joe

On Mon, 22 Sep 2008 18:03:18 -0700 (PDT), RAB <rabmissouri@yahoo.com> wrote:

>Thanks.  Your responses helped me realize the thread was probably
>behaving like it should.  I then found my dumb mistake.  I was using a
>boolean variable in OnOK() to check if the dialog box had been
>closed.  Within my thread function I constantly had if() statements
>checking for this boolean variable and if it was set then exit the
>thread.  However, I forgot that I had to set the variable to static or
>my project wouldn't build.  As a result, I assumed the variable would
>reset itself each time the dialog opened, but because it was static,
>it didn't.  There is probably a better and easier way to teminate the
>thread when the dialog closes?
>
>Thanks again,
>RABMissouri
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
9/23/2008 2:03:11 AM
On Mon, 22 Sep 2008 18:03:18 -0700 (PDT), RAB <rabmissouri@yahoo.com>
wrote:

>Thanks.  Your responses helped me realize the thread was probably
>behaving like it should.  I then found my dumb mistake.  I was using a
>boolean variable in OnOK() to check if the dialog box had been
>closed.

I don't know why you would do that.

>Within my thread function I constantly had if() statements
>checking for this boolean variable and if it was set then exit the
>thread.  However, I forgot that I had to set the variable to static or
>my project wouldn't build.

Adding keywords until it builds is not the best strategy. :)

>As a result, I assumed the variable would
>reset itself each time the dialog opened, but because it was static,
>it didn't.

Right. It should be a non-static member of the thread class. You always
have to think about object lifetimes, but if you apply the principles I
discuss in the page I linked to in my first message, it won't be a problem,
because the creator of the thread will turn off auto-deletion and thus own
the thread object and bear responsibility for deleting it (aka ending its
lifetime).

>There is probably a better and easier way to teminate the
>thread when the dialog closes?

I talk about that in the page I linked to in my first message.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
9/23/2008 3:16:12 AM
"RAB" <rabmissouri@yahoo.com> wrote in message 
news:c16134d4-0a84-42ad-895d-58162bb1709e@26g2000hsk.googlegroups.com...
> Thanks.  Your responses helped me realize the thread was probably
> behaving like it should.  I then found my dumb mistake.  I was using a
> boolean variable in OnOK() to check if the dialog box had been
> closed.  Within my thread function I constantly had if() statements
> checking for this boolean variable and if it was set then exit the
> thread.  ...  ...

That is a fundamentally unreliable solution.  You can't accomplish thread 
safety with 'if' statements.  The problem is that right after you execute 
such an 'if' there could be a thread switch, and the boolean condition could 
change before the thread executes its next statement.  So the results of 
your 'if' check have become obsolete.

As Joe shows, what you must do is make sure the main thread boolean remains 
in existence until _after_ the thread has exited.

-- 
Scott McPhillips [VC++ MVP] 

0
Scott
9/23/2008 4:11:11 PM
See below...
On Tue, 23 Sep 2008 12:11:11 -0400, "Scott McPhillips [MVP]" <org-dot-mvps-at-scottmcp>
wrote:

>"RAB" <rabmissouri@yahoo.com> wrote in message 
>news:c16134d4-0a84-42ad-895d-58162bb1709e@26g2000hsk.googlegroups.com...
>> Thanks.  Your responses helped me realize the thread was probably
>> behaving like it should.  I then found my dumb mistake.  I was using a
>> boolean variable in OnOK() to check if the dialog box had been
>> closed.  Within my thread function I constantly had if() statements
>> checking for this boolean variable and if it was set then exit the
>> thread.  ...  ...
>
>That is a fundamentally unreliable solution.  You can't accomplish thread 
>safety with 'if' statements.  The problem is that right after you execute 
>such an 'if' there could be a thread switch, and the boolean condition could 
>change before the thread executes its next statement.  So the results of 
>your 'if' check have become obsolete.
*****
I don't think this is a problem, because the Boolean is monotonic, that is, it can ONLY go
from TRUE to FALSE (for example, am-I-running) during the life of the thread.  So if you
set it TRUE, and it later goes to FALSE, nothing else can ever make it go TRUE until the
thread terminates.

The failure is in using a single static variable.  In this case, I would derive a thread
from CWinThread, and put the boolean in its class.  I'd probably implement the thread code
in the OnInitInstance.  But I'd have one boolean per thread, which is the only safe way to
do this under these conditions.

Monotonicity is a great advantage.
				joe
*****
>
>As Joe shows, what you must do is make sure the main thread boolean remains 
>in existence until _after_ the thread has exited.
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
9/23/2008 7:48:57 PM
Reply:

Similar Artilces:

Problem with blocking of main thread with other thread
I have a problem with blocking of main thread: My application contains an interpreter and I need to write a debugger for it. The mainframe creates a thread that is interpreting instructions. When I need to break execution of instruction thread, I use WaitForSingleObject(m_WaitEventHandle, INFINITE); in the interpreter thread. Everything works fine until the window is opened from the interpreter. Then the mainframe freezes. When I break execution in VC the call stack for interpreter thread shows: � NTDLL! � KERNEL32! � CDebugManager::CheckBreakpoints() � CInterpreterThread::Run() � _Afx...

Outlook 07 closes out
Open up Outlook 2007 to check email. Receive a message. Outlook has received an error. No other reason just that and closes. Running XP, even tried doing a different logon and it does the same thing. I do not want to reformat my pc uless I really need to. Have even unstalled and reinstalled. Same thing Are there any relevent entries in Event Viewer? "Ken" <kbishop53@woh.rr.com> wrote in message news:uTcAVBARIHA.4476@TK2MSFTNGP06.phx.gbl... > Open up Outlook 2007 to check email. Receive a message. Outlook has > received an error. No other reason just that and closes. R...

Caption Form doesn't fill in correctly
On some docs, notably saved from Rhapsody Report, the Word Caption form fills in Right to Left instead of Left to Right. Makes it hard to work with it. How do I determine what is wrong and fix it? Memo to Microsoft: This problem would be easier to define if users could attach screen prints... Presumably this happens because your Caption style is defined as right-aligned? -- Suzanne S. Barnhill Microsoft MVP (Word) Words into Type Fairhope, Alabama USA http://word.mvps.org "HighlandsHillbilly" <HighlandsHillbilly@discussions.microsoft.com> wrote in m...

When I copy down into the next cell the formula changes correctly.
When I copy down into the next cell the formula changes correctly however the result keeps reading from the line I copied from. It is not an absolute cell. The formula is correct. If I delete the result and type the formula manually into the cell it works. Why would this be - Is there a button I need to tick off? It only seems to happen on my computer Calculation is probably set to manual. To change it, choose Tools>Options. On the Calculation tab, select Automatic Click OK Jason30 wrote: > When I copy down into the next cell the formula changes correctly however the > result k...

Closing a location
We are closing one of our 7 locations with plans to re-open a new location later this year. How do I close a location but still keep the History from that store? I see the delete key in HQ manager under Admin>stores, but does that blow away the history in my database? By selecting delete, will that also remove that store from all of the worksheet processing we do? I will want to use the equipment from the closed store in the new store. Has anyone had to deal with this before? Thanks, Tom ------=_NextPart_0001_30D2555D Content-Type: text/plain Content-Transfer-Encoding: 7bit G...

Problems closing Windows Mail
When I try to close WM I get a box saying that WM has stopped working and Windows is looking for a solution. It then restarts and it is suggested I go to check for updates. I don't need to as I keep my computer up to date with all available updates but I did anyway and no updates were availoable. I have scanned for viruses etc but computer is clear. Could WM have become corrupted in some way? How can I solve this? Cannot find a download for WM itself, only Windows Live Mail but I would rather not go down that road. No improvements or updates for Windows Mail have been release...

Where is my thread?
I posted a question about "Search for a value in multi-dimensionla array" an hour ago; where did that go? On 5/17/2010 17:38, Rick wrote: > I posted a question about "Search for a value in multi-dimensionla array" an > hour ago; where did that go? If you mean the one beginning with "Seach", posted almost half an hour before this one, it is there. :) On 5/17/2010 11:51 AM, Jackie wrote: > On 5/17/2010 17:38, Rick wrote: >> I posted a question about "Search for a value in multi-dimensionla >> array" an >> hour ag...

Excel 2003 does not prompt to save changes when closing?
We just got Excel 2003 installed on our computers at work and I noticed that when I make updates to an Excel document, that the program does not automatically prompt me to save the changes? Is there a setting somewhere that I need to change for this? This is gonna be fuzzy. There have been a couple posts in the last week or so that complained of the same problem. I think those users wrote back saying that there was a misbehaving addin causing the trouble. But I don't remember the name of that addin. You could search google to see if you could find it (I couldn't). Or you could...

How to close a batch (run Z report) if register is disabled
I was wondering.. since you can only Z-report from a register (not from Manager), how do you properly close a batch if, say, a register is disabled in the middle of a shift (power outage, etc)? thanks! -- RG Robert, Where is the Database? i.e. Is database locally on register? Is this a single lane store? If there is a power outage, the only way to close out the batch is to wait until the power comes back on. As I said before if your db is on another machine, you can go into Store Operations Administrator --> Configuration --> Database Tab on that machine and change the Regis...

Simple Thread
I have created a thread in my MFC Dialog based application, in the thread function i want to have access to a user interface control that is attached to the main dialog. How can I do it? Regards, Mystique Mystique wrote: > I have created a thread in my MFC Dialog based application, in the thread > function i want to have access to a user interface control that is attached > to the main dialog. > How can I do it? > > Regards, > Mystique > > Indirectly, by posting a message to the main thread asking it to update the control. http://www.mvps.org/vcfaq/mfc/12.ht...

Diaglog/Threading Data Exchange Question
Greetings, I have learned a lot from all of you, and I hope to over come my latest road block. I have a smal IRC Chat client I am making. I have a Dialog Box with Control and I use a worker thread for connecting to IRC - That Thread will update controls on the Dialog by sending PostMessages. Now my problem is in the ListBox Control that I have extended to do popup menu with various commands. I need to be able to read that controls methods from within the Thread. so I need to do this from within my IRC Socket thread: (code not exact - pseudo code) CListBoxEx myUsers; //Defined in my ...

Need Help with Busy Dialog Thread
my application would perform a task. I want to stop the user from using the application's GUI untill the the BG task is finished. At first using Modal Dlg did not do the trick as every one now (apart from me) the the CDialog::DoModal() function has to return some how. So, I made a bit of research on the net and found a trick to display the Dialog using CWinThread derived class without stoping the main app window for executing the background task as follows: (1) In your header file define a CWinThread-derived class... class CDialogThread : public CWinThread { DECLARE_DYNCREATE(CDial...

Killing thread from outside thread in MFC App
Hi, Thanks to all those who offered advise on my last query. I successfully used the worker thread method to give control back to the dialog box whilst background processing was being carried out. The issue I have now is closing that thread externally. The method I've used to create the thread uses a volatile boolean variable. Whilever it is set to TRUE, the thread remains alive. However, when I set the variable to FALSE from the calling process (user wants to end processing), it has no effect. The thread continues to run. I thought that declaring the variable as 'volatile'...

add fields to query in closed data base
thank you Can I change (record source ) for field in report in (close) data base by code using current (open ) data base. Field1 record source Or field source = Playername Change to Field1 record source Or field source =PlayerN --- Is possible to add field to query in closed data base by code using current open database notes query is created in close database the query contain fields I want add field to this query ...

To Thread or not to thread
I am using a CRecordset object to retrieve data from a remote server. The time to retrieve the data is highly variable because of network traffic etc etc etc and has varied from a few ms to almost a minute. Question: Is it a good practice to use a worker thread to handle the database exchange to avoid having my main thread block for long periods of time? I assume that I would let the exchange timeout and then check the return status and a global variable to determine if it should keep trying until it returned data ( might be null but that's ok). Ron H. Ron, While it may be a tin...

MFC- Closing application
Hello, I have a problem within a MFC Application. I want to close this MFC Application when a event comes, but I didn't have any OnCancel member Function in this App. Is it any Function who allows me to close a MFC Application without more development? thanks St�phane You can try with PostQuitMessage(0); -- Bjarne Nielsen "Stefan Ros�" <s.rose@resa.de> skrev i en meddelelse news:eNx3s$%234DHA.1852@TK2MSFTNGP10.phx.gbl... > Hello, > I have a problem within a MFC Application. I want to close this MFC > Application when a event comes, but I didn't have any O...

Contacts displays correct email but display as info is incorrect.
I'm running Outlook 2007 SP1 MSO 12.0.6425.1000 I'll open a contact say jane doe and here's what I'll see for the contact info/card Email: jane.doe@aol.com Display as: Joe Smith (jsmith@cox.net) NOTE: a valid email address for another contact of mine I'll double click the email address to open the properties and I'll see garbage characters for the display name as well as the email address. How I have to fix is cut the valid email address, wipe out the email & display info, paste the valid email address into notepad the copy and paste back into ...

Anyone care to offer advice for my Client / Server threading model
I'm a bit of a sockets newbie and not too sure what the established ways of handling CAsyncSockets are. I need to handle two way comms between two or more handheld pcs and a server. WIth the server I've got: 1 Thread polling for new connections 1 Thread per client connection. The client thread is stuck in a loop called from CWinThread::InitInstance and sits and calls the CAsyncSocket::Receive function until something arrives. It uses peekmessage and postmessage in this loop to see if the app wants me to send anything to the client. This is working erratically though - peekmessage know...

write DOS command to startup/close outlook
Hi, I would like to write a command to startup/close outlook in DOS prompt, can somebody give me some help for this? Is Outlook.exe brings the command-line switches to startup or close the program outlook? Regards Yiqing.Qian ...

Displaying dashed or dotted lines correctly in logarithmic scale?
I'm observing a problem already described in Article 214389 (regarding tredlines in Excel2000 displayed incorrectly). I'm unable to print dashed or dotted lines in logarithmic scale correctly, even though they appear correctly on screen and in print preview (!). A dashed or dotted line does not appear to have any dashes, or only a portion of the line may have dashes, or the dashed line appears to be distorted, or of uneven spacing. I guess it's an unresolved bug. I'm only surprised it's been known since Excel2000, and not corrected! Are there any solutions to the pr...

Threads in MFC
Hi to all... I've made a multithreaded Application (with MFC of course) and it works well on some PC, but in others PC's with the same OS (Win2000SP4) it throws "access Violation" immediatly just when a thread starts. (No matter which one... just the first). I've supposed it was some lib missing, and I've installed VC6... it didn't solve anything. any suggestion? I had a similar problem when I didn't realize I was trying to distribute a DEBUG version of the program. Otherwise, can you post a code snippet? On Mon, 19 Apr 2004 16:55:16 +0200, Nicola Bam...

multi-threaded control not destroyed on exiting the page?
I have created an ActiveX control (subclassing COleControl) which uses the afxRegFreeThreading model, and I have a small sample web page which inserts the control using an <object> tag. I noticed that when my page places the control inside the <head> tag, the control's destructor is called when my browser goes to a different page. But if the control is inside the <body> tag, the destructor is not called when I leave the page. The control's destructor is eventually called when I exit my browser, but I fear that my control is continuing to occupy system resources unt...

MS Pub 97 would not close
Recently I noticed a strange behavior of my MS Pub 97, it would not close. In fact, when I click Close or Exit in File menu, the publication or application closes, I cannot see it anywhere. However, when I try to reopen publication, I'm getting error message saying that this publication is still open... The only way to "close" it is to reboot computer. What's going on? How to fix it? In the past, for many years, there was no such problem. -- Ilya Zeldes Fort Myers, Florida Might try a re-install. Does this happen in safe mode? Have you changed printers lately? Do y...

MAD monitoring thread?
I have Exchange 2000 running on a Win2K Server. I have a trust to an NT4 domain with an Exchange 5.5 Server. Both are in the same site and my goal is to move the mailboxes and whatnot to the Exchange 2000 box. So far, just getting 2000 to operate has been a problem. It's installed and running but my MS Exchange Info Store and MTA stacks won't start in the services. If I reboot, they start, but stop within a few minutes. I have errors in my application log for MSExchangeSA that say, "The MAD monitoring thread was unable to read its configuration from the DS." I have MSEx...

You don't have access to the toolbar. Great plains will close.
This error occurs when loging in to Great Plains from some but not all workstations. And only into some databases. Other databases open fine. Great Plains 7.5, Windows 2000. Could someone post the uninstalation and clean install instructions including patching it to the latest version? Thanks very kindly Milan Security is controlled on a per user per company basis. Find a user who can log in and use Standard Security (Setup >> System >> Security) or Advanced Security's By Dictionary view (Setup >> System >> Advanced Security) to give access back to the Tool...