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' would allow for the 
thread to be closed externally. What else do I need to do to?

Thanks,
Rob 


0
4/14/2007 12:43:30 AM
vc.mfc 33608 articles. 0 followers. Follow

8 Replies
539 Views

Similar Articles

[PageSpeed] 42

Rob wrote:
> 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' would allow for the 
> thread to be closed externally. What else do I need to do to?

Kind of hard to guess without a code outline of the thread.

-- 
Scott McPhillips [VC++ MVP]

0
Scott
4/14/2007 3:22:37 AM
See below...
On Sat, 14 Apr 2007 10:43:30 +1000, "Rob" <millerman@ozemail.com.au> wrote:

>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.
****
This is one of the most common paradigms for shutting down a thread.  So it should work;
show your code.  
				joe
****
>
>I thought that declaring the variable as 'volatile' would allow for the 
>thread to be closed externally. What else do I need to do to?
>
>Thanks,
>Rob 
>
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)
4/14/2007 3:40:54 AM
Sorry, here's an extract of my code:

//Declaration:

 static UINT MyThreadProc(LPVOID p);
 void MyThreadProc();
 volatile BOOL running;

// begin thread when user presses Go
void CSmartTimerDlg::OnGo()
{
    .
    .
    .
    running = TRUE;
    AfxBeginThread(MyThreadProc, this);
}

UINT CSmartTimerDlg::MyThreadProc(LPVOID p)
{
     CSmartTimerDlg * me = (CSmartTimerDlg *)p;
     me->MyThreadProc();
     return 0;
}

void CSmartTimerDlg::MyThreadProc()
{
     processing code here
}

//When user presses clear button to cancel on dialog box, end thread
void CSmartTimerDlg::OnClear()
{
     running = FALSE;
}


"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
news:t7j0231los01ru48681skt8bv4ockp12tt@4ax.com...
> See below...
> On Sat, 14 Apr 2007 10:43:30 +1000, "Rob" <millerman@ozemail.com.au> 
> wrote:
>
>>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.
> ****
> This is one of the most common paradigms for shutting down a thread.  So 
> it should work;
> show your code.
> joe
> ****
>>
>>I thought that declaring the variable as 'volatile' would allow for the
>>thread to be closed externally. What else do I need to do to?
>>
>>Thanks,
>>Rob
>>
> Joseph M. Newcomer [MVP]
> email: newcomer@flounder.com
> Web: http://www.flounder.com
> MVP Tips: http://www.flounder.com/mvp_tips.htm 


0
4/14/2007 4:56:39 AM
Rob schrieb:

> Sorry, here's an extract of my code:
> 
> //Declaration:
> 
>  static UINT MyThreadProc(LPVOID p);
>  void MyThreadProc();
>  volatile BOOL running;
> 
> // begin thread when user presses Go
> void CSmartTimerDlg::OnGo()
> {
>     .
>     .
>     .
>     running = TRUE;
>     AfxBeginThread(MyThreadProc, this);
> }
> 
> UINT CSmartTimerDlg::MyThreadProc(LPVOID p)
> {
>      CSmartTimerDlg * me = (CSmartTimerDlg *)p;
>      me->MyThreadProc();
>      return 0;
> }
> 
> void CSmartTimerDlg::MyThreadProc()
> {
>      processing code here
> }

Abnd what does the "processing code" do? It has to check the boolean variable 
inside its processing loop and leave the ThreadProc when it is set to true. just 
declaring a boolean somewhere and setting it does not cause a thread to quit. 
The thread has to check the boolean and react on it.

> //When user presses clear button to cancel on dialog box, end thread
> void CSmartTimerDlg::OnClear()
> {
>      running = FALSE;
> }

Norbert

0
nunterberg (207)
4/14/2007 7:31:51 AM
On Sat, 14 Apr 2007 14:56:39 +1000, "Rob" <millerman@ozemail.com.au>
wrote:

> volatile BOOL running;
>
>// begin thread when user presses Go
>void CSmartTimerDlg::OnGo()
>{
>    .
>    .
>    .
>    running = TRUE;
>    AfxBeginThread(MyThreadProc, this);
>}

>void CSmartTimerDlg::OnClear()
>{
>     running = FALSE;
>}
>

It is not sufficient to set a boolean variable to false to stop the
thread :)

I'm sure that Joe's encyclopedia will help you; you might read his
article about worker threads (there is a paragraph about thread
shutdown, too):

http://www.flounder.com/workerthreads.htm

MrAsm
0
mrasm (715)
4/14/2007 10:01:15 AM
Rob wrote:
> 
> //When user presses clear button to cancel on dialog box, end thread
> void CSmartTimerDlg::OnClear()
> {
>      running = FALSE;
> }

If the thread code does not regularly check the value of 'running' then 
there is no reason to expect that the thread should do anything when you 
change 'running'.  You seem to have a write-only variable here.

-- 
Scott McPhillips [VC++ MVP]

0
Scott
4/14/2007 12:06:30 PM
Also, Rob, if you plan to set the value of running outside of the loop that 
is checking it, assuming that's how you exit the thread loop, you may want 
to make it a volatile variable to force the optimizer to check it each time.

Tom

"Rob" <millerman@ozemail.com.au> wrote in message 
news:46205f13$0$13135$5a62ac22@per-qv1-newsreader-01.iinet.net.au...
> Sorry, here's an extract of my code:
>
> //Declaration:
>
> static UINT MyThreadProc(LPVOID p);
> void MyThreadProc();
> volatile BOOL running;
>
> // begin thread when user presses Go
> void CSmartTimerDlg::OnGo()
> {
>    .
>    .
>    .
>    running = TRUE;
>    AfxBeginThread(MyThreadProc, this);
> }
>
> UINT CSmartTimerDlg::MyThreadProc(LPVOID p)
> {
>     CSmartTimerDlg * me = (CSmartTimerDlg *)p;
>     me->MyThreadProc();
>     return 0;
> }
>
> void CSmartTimerDlg::MyThreadProc()
> {
>     processing code here
> }
>
> //When user presses clear button to cancel on dialog box, end thread
> void CSmartTimerDlg::OnClear()
> {
>     running = FALSE;
> }
>
>
> "Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
> news:t7j0231los01ru48681skt8bv4ockp12tt@4ax.com...
>> See below...
>> On Sat, 14 Apr 2007 10:43:30 +1000, "Rob" <millerman@ozemail.com.au> 
>> wrote:
>>
>>>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.
>> ****
>> This is one of the most common paradigms for shutting down a thread.  So 
>> it should work;
>> show your code.
>> joe
>> ****
>>>
>>>I thought that declaring the variable as 'volatile' would allow for the
>>>thread to be closed externally. What else do I need to do to?
>>>
>>>Thanks,
>>>Rob
>>>
>> Joseph M. Newcomer [MVP]
>> email: newcomer@flounder.com
>> Web: http://www.flounder.com
>> MVP Tips: http://www.flounder.com/mvp_tips.htm
>
> 

0
tom.nospam (3240)
4/14/2007 2:21:22 PM
Unfortunately, the critical code, showing where you test it, is missing.
					joe

On Sat, 14 Apr 2007 14:56:39 +1000, "Rob" <millerman@ozemail.com.au> wrote:

>Sorry, here's an extract of my code:
>
>//Declaration:
>
> static UINT MyThreadProc(LPVOID p);
> void MyThreadProc();
> volatile BOOL running;
>
>// begin thread when user presses Go
>void CSmartTimerDlg::OnGo()
>{
>    .
>    .
>    .
>    running = TRUE;
>    AfxBeginThread(MyThreadProc, this);
>}
>
>UINT CSmartTimerDlg::MyThreadProc(LPVOID p)
>{
>     CSmartTimerDlg * me = (CSmartTimerDlg *)p;
>     me->MyThreadProc();
>     return 0;
>}
>
>void CSmartTimerDlg::MyThreadProc()
>{
>     processing code here
>}
>
>//When user presses clear button to cancel on dialog box, end thread
>void CSmartTimerDlg::OnClear()
>{
>     running = FALSE;
>}
>
>
>"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
>news:t7j0231los01ru48681skt8bv4ockp12tt@4ax.com...
>> See below...
>> On Sat, 14 Apr 2007 10:43:30 +1000, "Rob" <millerman@ozemail.com.au> 
>> wrote:
>>
>>>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.
>> ****
>> This is one of the most common paradigms for shutting down a thread.  So 
>> it should work;
>> show your code.
>> joe
>> ****
>>>
>>>I thought that declaring the variable as 'volatile' would allow for the
>>>thread to be closed externally. What else do I need to do to?
>>>
>>>Thanks,
>>>Rob
>>>
>> Joseph M. Newcomer [MVP]
>> email: newcomer@flounder.com
>> Web: http://www.flounder.com
>> MVP Tips: http://www.flounder.com/mvp_tips.htm 
>
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)
4/14/2007 10:36:27 PM
Reply:

Similar Artilces:

Kill Excel silently
Hi, I batch file that queries a database and creates a flat file. I want to start Excel, make graph of the data and save it as an htm file. I then want to get out of Excel. I want to do this automatically twice daily (eg at midnight). I use Scheduled tasks and a macro to start Excel and create the graph But Excel won't quit so I've set the ask Scheduler to stop Excel afte 1 minute. Here's the problem ... I get a message saying that Excel has terminate unexpectedly and would I like to send an Error Report to Microsoft?! I cannot turn this message off no matter what Service I st...

talking to CView from a thread?
Hi, In a thread which is created under CView->OnInitialUpdate, I will try to get the handle to CView from this thread. Codes are like, CWnd *pWnd =CWnd::FromHandle((HWND)lpParam); CWnd *pParent = pWnd->GetParent(); lpParam is the m_hWnd of CView. OK, either pWnd or pParent must be the CWnd for CView, is that right? (which one is? ). I tried to recast pWnd or pParent to CMyView and try to control one of edit control which belongs to CMyView? but coundn't. any comments? thanks pat/ Patrick Zou wrote: > Hi, > > In a thread which is created under CView->OnIniti...

worker threads #2
Hi all, I have few questions on worker threads on click of start button i call AfxBeginThread(threadProc) on stop i try to exit from the threadproc. again i click on START which intern calls the AfxBeginThread.. for a new set of data transfer... my question is... will the previous thread be removed and new thread called threadproc will be created??? is it right to create / exit every time of start/Stop? Next i the ThreadProc..in case WAIT_OBJECT_0 signalled state i am incrementing indexcount of data[indexcount] will the data[] will be transferred in right sequence?? do i need to use anythin...

SendMessage fails in UI thread
Hi guys, I am maintaining VC6++ MFC application that creates UI thread. This application basically tests all functions of hardware product by calling a set of test functions according to user selection. UI thread sends message to main frame to handle a specific case(to make a database record). It works(at least looks) well so far but for some reason, SendMessage() started to return FALSE(but message is handled correctly). Recent changes were that, for some tests, UI thread creates worker threads instead of calling functions. I don't know if these changes are related to this faulty situati...

Hyper-Threading Technology for XP with Excel 2000
Attention to: Microsoft Expert My computer setting is Dual-XEON 2.66, 1GB RAM with Windows XP Professional. Hyper-Threading Technology is enabled, therefore, I am able to see four logical Processors. However, when I open single Excel 2000 spreadsheet for calculation, it consumes 25% of CPU and 130MB RAM on computing resources. If I disable Hyper- Threading Technology, then it displays only 2 CPU processors only, and I try to run the same single Excel 2000 spreadsheet for calculation, it consumes 50% of CPU, of course, the speed of calculation is faster. Could you tell me why Hype...

What i need to do to pick e-mail with ms outlook 2003 from outside
I follow the intructions on the work place about setting up but still do not work. I may need to open ports on my firewall ?? I can acces almost everything from outside Workplace, remotedesktop, exchange web access. Please guide me. Regard, Saulo If you have a firewall software on your desktop Disable it for a second, Shut it down and than try to access OWA, OWA will run on port 80 to 443 if your work place has done the redirection, anyway, if you can get to the internet you should be able to get to your OWA at work For RDP(remote desktop) works on port 3389 TCP Most of the firewalls...

kill
wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kill you right now wo will kil...

Important restore a server a ups killed with large amount of data
Hello, A ups died taking out one of my sbs 2003 servers. now there is a lot data on this machine i am talking roughly 3 tb of data. Here is where is sites, sharepoint and sql are toast. completely a uninstall and reinstall don't fix it if anything it broke more. I have a backup from 3 days ago from sbs backup I also have a image based backup from 2 months ago. what is the best way to get this server up and running without taking the whole day tomorrow. can i just use ntbackup from the sbs backup i have and do a restore on the server and tell it to skip the data partit...

MFC GetParent CWnd* return
Hi, GetParent returns the cached pointer maintaned by MFC framework,right, So I don't have to be doing any delete on the returned pointer,Am I right? By digging a bit into wincore.cpp, this is what I understand and also the documentation of GetParent says:-" The returned pointer may be temporary and should not be stored for later use". So I feel my understanding is right. Correct me if I am wrong. Also if I am right, Can I get a list of functions which returns framework's cached values, if not complete atleast something to give some feeling that these functions behave one...

Problem with SQLGetData in VC++/MFC
Hi All, I am building desktop appln. in VC++ 6/MFC with Oracle DB connection. Please see the below API which works fine on windows XP but displays some garbage value(junk chars.) when used on windows 2000, 2003 server. When SQL_BINARY datatype is changed to SQL_CHAR it is displaying correct values but the processing time of getting the data is increasing significantly(which is not avoidable). rc = SQLGetData(hStatement, 1, SQL_BINARY, vl_buf, ...

About MFC CRect class
This is a multi-part message in MIME format. ------=_NextPart_000_000C_01C468ED.2AD18AD0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I was wondering: if CRect coordinates, like CRect::left, CRect::top, = CRect::right and CRect::bottom are long value type, why the functions = CRect::Height() and CRect::Width() return int value type? TIA. ------=_NextPart_000_000C_01C468ED.2AD18AD0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4...

Re: Launching Internet Explorer from my MFC App
Hi All Would anyone out there know how to launch Internet Explorer with a specific URL from an MFC App. I would like to have a menu item that when selected launches Internet Explorer. Thanks in advance Hi, You can use ShellExecute(Ex) passing the url as the file, this will automatically start the associated application which is in the case of a url would be your default browser. ShellExecute(handle, NULL, "http://www.google.com", NULL, NULL, SW_SHOWNORMAL); Hope this helps Chris Taylor "LarryM" <larryman.nospam@bigpond.net.au> wrote in message news:XDKcb.12...

Multi thread download
hi all, I want write a programe multi thread downloading use window's functions such as: InternetOpen, InternetConnect, HttpOpenRequest, ...etc, but i have problem query a segment of file from server, i try to add header request : strHeader[1024]; _stprintf(strHeader, _T("Range: bytes=%d-\r\n"),dwStartDownload); if(!::HttpAddRequestHeaders( _hHTTPRequest, strHeader, _tcslen(strHeader), HTTP_ADDREQ_FLAG_ADD)){ ::InternetCloseHandle(_hHTTPRequest); ::InternetCloseHandle(_hHTTPConnection); ::InternetCloseHandle(_hHTTPSession); return false; } _stprintf(str...

Threads #7
I was wondering if someone could tell me how to implement a couple of threads. I have an MFC application which launches a Command line application using 4 different commandline arguments. This works fine using CreateProcess, but I also want to update a progress bar to the amount of how long the command line application stays active. I created a thread to update the progress bar and it works, but I can't figure out how to update the progress bar at the same time that the exernal process is active. The program always waits until the process is complete before updating the progres...

Media Player in C++ App
I've searched the threads but haven't seen this problem yet. Using VC++6 sp6 MFC. I have embedded the Media Player Active X into a dialog box. The resources show the proper media player default skin. Have filled out the properties and URL file (a MP3 file). When compiled, everything checks out. When I open the dialog box with DoModal(), the dialog box appears, the file plays but no media player is visible. Tried same with video file. sound is heard but again no player. Right mouse clicks bring up menu items and such and about shows the proper media player (9). First shot I just ...

Kill Sound Effects
Whenever I switch Outlook folders or switch messages within a folder I get this annoying sound (P-chew with an accent on the chew). I have tried turning off any references to sound alerts in Outlook options. Also went to Windows Control Panel sounds and turned off Office sounds. But I still get the sound. Where is the control for it hiding? Running Outlook 2000 SP-3 and Win XP Home SP-2. ...

View both incoming/outgoing messages by Thread or Conversation ? #2
Is it possible to view messages in outlook 2003 by Thread or Conversation, both incoming and outgoing, in a single folder, or Inbox, just like Outlook Express News Reader. For example: + Sent Message + Received Reply +Sent Message or Replied + Received Reply I tried using Arrange by Conversation Option in outlook 2003 Inbox Folder, but its just showing Inbox Messages, not Sent Items Messages. Best Regards, Luqman ...

Creating MFC child dialogs and windows in DLL.
Hi, I need to write some kind of plug-in, which are implemented as separate dll's. I already wrote a few plugins for this program using MFC and it worked ok, but now I need to create some GUI inside a plugin. I have an interface like that class IModule { public: virtual void ShowConfDialog( HWND hwndParent ) = 0; virtual HWND CreatePanel( HWND hwndParent ) =0; // create child window, position and size will be // controlled by a parent window. } But when creating a child windows in MFC I nee...

kill process
Hi, With VBS, how can i kill a process which I own and with a name contains a fixed string like 'blabla' Thanks in advance bob123 wrote: > With VBS, how can i kill a process which I own --- <code> --- ' walk the process list demo, using wmi v1.5, jw 09Jul00 ' (note: this demo adapted from msdn mag, Apr 2000, wmi article by ???) ' 12Jul00: modified to demo Process.Terminate Option Explicit Dim sProcList ' as string Dim oWMI, Process ' as objects Dim oShell ' as object Dim sNotepad ' as string ' launch...

How Can I Find My Threads?
I have posted several questions in here, but cannot see anywhere that I can go directly to my threads, as I can in other Windows Forums. It is almost impossible to scan thru hundreds of messages to see if my questions have been answered. Is there a link somewhere to do that? Did you try looking in your closet? Or how about top right-hand corner... icon to the left of "Help". You'll see your threads at the bottom of the next page. -- Earthling "JoeyC2" wrote: > I have posted several questions in here, but cannot see anywhere that I can >...

thread question
I am using VS 2008. I need to process message on accounts. I would like to create thread for each account, and in each of the account thread, I will do the process in order the message comes in. For example: Accounts 1, 2 and 3. Accounts 1 has 2 messages, account 2 has 3 messages and account 3 has 3 messages. I would like to create 3 thread: 1 for account 1, 1 for account 2, and 1 for account 3. In thread 1 for account 1, I want to process the 2 messages in order they come in: message A, then B In thread 2 for account 2, I want to process the 3 messages in order they come in....

What is the correct way to kill a search in progress in Outlook 2007?
I was doing a simple search in Outlook, it didn't find it in the Inbox, so I told it to "Try searching in all mail items". After five minutes I gave up but couldn't find any way to cancel the search. Not CTRL C, CTRL Break, escape, clicking anywhere on the Outllok window, etc. I ending up killing it in Task manager. What is the correct way to kill a search in progress in Outlook 2007? The x to the right of the search field should do it. -- Diane Poremsky [MVP - Outlook] Outlook Tips: http://www.outlook-tips.net/ Outlook & Exchange Solutions Cen...

show discussion thread for mailinglists
Hello, I use outlook as my mailclient and so I also get some mailinglist (i.e. DIRECTXDEV@DISCUSS.MICROSOFT.COM). My problem is that using outlook (2003) it is quite hard to follow the discussion. Since it is kind of hard to see what mail is a reply to what. In outlook express it works just fine you have some kind of treeview with indents that clearly show the discussion thread. Only it seems like outlook is not capable of doing that. Or is there a way. Maybe a plugin or something .... ? ...

System Lockout with MFC
Hello, I was wondering how I can do something similar to a lockout in Windows 2000, where when you press Windows + L you can lock your desktop, however I would like to not use the standard API (which just causes the Computer is Locked dialog box to appear). I would rather like to make it so that when my dialog appears, all other dialogs and the system tray and everything disappears,you can't CTRL+ALT+DEL and you must deal with my dialog box by entering in a correct password and clicking ok in order to unlock the sytem. Any suggestions? Sincerely, James Simpson Straightway Techno...

Timers and Threads
Hello, I have a class in which I use System.Threading.Timer. The callback function should send a message using TCPClient. Since the Callback function is in an another thread this doesn't work! How do I Invoke a function in the class thread from the callback function? The Class is not a Form class! // Anders -- English is not my first language so any error, insults or strangeness has happend during the translation. Please correct my English so that I may become better at it! Anders Eriksson wrote: > Hello, > > I have a class in which I use System.Thre...