threads #2

I have a server/client application that communicates using threads. The 
server class uses a while loop inside a thread to wait for new connections 
in accept state, like this:

var a = new var( );

while( (server.Accept(connection)) )
{
......
......
}

I have declared a variable (var) right before this loop which uses memory. 
I want to free/delete this variable at the end of the while loop, but the 
control never reaches there.

How can I make sure that this variable gets deleted before the server side 
exits?

Thanks.
Jessica 


0
12/20/2005 11:58:27 AM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
672 Views

Similar Articles

[PageSpeed] 55

Jessica Weiner wrote:
> I have a server/client application that communicates using threads. The 
> server class uses a while loop inside a thread to wait for new connections 
> in accept state, like this:
> 
> var a = new var( );
> 
> while( (server.Accept(connection)) )
> {
> .....
> .....
> }
> 
> I have declared a variable (var) right before this loop which uses memory. 
> I want to free/delete this variable at the end of the while loop, but the 
> control never reaches there.
> 
> How can I make sure that this variable gets deleted before the server side 
> exits?
> 
> Thanks.
> Jessica 

What makes the thread exit?  Whatever you are doing inside the loop to 
exit should be changed.  Perhaps the use of 'break' in the loop will let 
you exit the loop before exiting the thread.

-- 
Scott McPhillips [VC++ MVP]

0
Scott
12/20/2005 1:25:18 PM
Jessica Weiner wrote:

> I have a server/client application that communicates using threads. The 
> server class uses a while loop inside a thread to wait for new connections 
> in accept state, like this:
> 
> var a = new var( );
> 
> while( (server.Accept(connection)) )
> {
> .....
> .....
> }
> 
> I have declared a variable (var) right before this loop which uses memory. 
> I want to free/delete this variable at the end of the while loop, but the 
> control never reaches there.
> 
> How can I make sure that this variable gets deleted before the server side 
> exits?
> 
> Thanks.
> Jessica 
> 

Jessica:

Your code doesn't look right. It should be:

var* pa = new var( );

But why are you "new"ing this variable in the first place? Why can't it 
be on the stack?

var a;

Then any memory contained in the "a" object will be freed by its 
destructor (assuming it is written correctly). This is a simple example 
of the technique called RAII. If you cerate your variable on the heap, 
then you must wrap it in a smart pointer to get the same effect. But 
"stack semantics" is almost always the way to go.

David Wilkinson
0
no-reply8010 (1791)
12/20/2005 1:45:51 PM
"David Wilkinson" <no-reply@effisols.com> wrote:
> Your code doesn't look right. It should be:
>
> var* pa = new var( );
>
> But why are you "new"ing this variable in the first place? Why can't it be 
> on the stack?

Thanks for your reply. I will try what you suggested.

Jess 


0
12/20/2005 2:36:23 PM
On Tue, 20 Dec 2005 11:58:27 GMT, "Jessica Weiner" <jessica@gmail.com>
wrote:

>I have a server/client application that communicates using threads. The 
>server class uses a while loop inside a thread to wait for new connections 
>in accept state, like this:
>
>var a = new var( );
>
>while( (server.Accept(connection)) )
>{
>.....
>.....
>}
>
>I have declared a variable (var) right before this loop which uses memory. 
>I want to free/delete this variable at the end of the while loop, but the 
>control never reaches there.

It sounds like your loop never exits, which is bad, because it implies your
thread runs forever, even while the program is shutting down. To understand
why that's bad and what to do about it, see:

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

Ideally, you'll replace your loop condition with an efficient, non-blocking
call, that will allow you to detect thread exit requests.

>How can I make sure that this variable gets deleted before the server side 
>exits?

Assuming you really do need to allocate it dynamically and not make it a
local variable as David suggested, you could use some type of smart
pointer, such as std::auto_ptr. This will take care of all loop exits and
returns, including exiting via an exception, e.g.

void ThreadFunc()
{
   std::auto_ptr<T> x(new T);
   for (;;)
   {
      switch (wait_for_connection())
      {
      case QuitRequest :
         exit loop and thread
      case GotConnection :
         ...
      case Error :
         ...
      default :
         ...
      }
   }
}

Note that x will be destroyed only if ThreadFunc returns, which does not
occur if you call ExitThread or AfxEndThread, hence the usual advice not to
use those functions. Another consideration is whether or not ThreadFunc
should put everything inside try/catch. If you don't do this, then an
uncaught exception will not only kill the thread, it will bring the whole
program down. This may well be the right thing to do, but if it isn't, you
can fix it. However, if your program is assuming a thread that exits
performed its job successfully, it may have to start taking thread exit
codes (or some other expression of thread state) seriously.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
12/20/2005 3:43:54 PM
Reply:

Similar Artilces:

Converting a number to 2 decimal places
I would like to be able to type a number into a cell and have i automatically converted to a number with the last 2 numbers to th right of the decimal point. For example, if I typed in 1234, it woul become 12.34. How can I do that -- mattsla ----------------------------------------------------------------------- mattslav's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2403 View this thread: http://www.excelforum.com/showthread.php?threadid=37648 Tools>Options>Edit Check Fixed decimal places Set for 2 Does that help? Ron -- Ron Coderre -------------...

can i create a modalless dialog box in worker thread.
hi guys, is it possible to create a modalless dialog box in the worker thread, actually we have try this but we got error that is" you cannot create object with new operator in the worker thread " but i don't know what is the actual reason behind this. actually i am trying to create a modalless dialog box from main dialog box and i want to perform openGL programing on both the dialog box in such a manner so that they do not collapse or crash each other because at one time only one rendering device context should reside in the memory if we want to create more then one device cont...

Search Attachments #2
How would you setup an outlook find/search to actually find something in the attached file, either in the subject or the body of the attached file? Is there a way to do this? Outlook's search doesn't do attachments. -- 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/ Outlook & Exchange Solutions Center: http://www.slipstick.com Join OneNote Tips mailing list: http://www.onenote-...

Public Folder Help #2
I have set permissions for users on public folders that contain contact groups. They used to work fine. Now when users logged into certain computers users are denied permissions. But they can log in on another computers with the same username and their permissions work fine. What can be causing this problem? Thanks ...

XmlSerializerNamespaces not working the same in dotnet 2.0 as #2
Hi, I am having trouble serializing an object in dotnet 2.0. I am using theis method public static string Serialize(object o, string defaultNamespace) { //create empty namespace to prevent namespace output XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", defaultNamespace); //create serializer XmlSerializer ser = new XmlSerializer(o.GetType()); using(StringWriter writer = new StringWriter()) { //use custom writer to prevent root 'xml' tag output XmlNoPrefixTextWriter xwriter = new XmlNoPrefixTextWriter(writer); xwriter.Formatting = Format...

Desktop Search in Outlook 2007 beta 2
I am running the 2007 beta 2 for Office on Windows XP. When I open Outlook I get a message saying I need to click an area to enable desktop search. I do and it gets halfway through the installation. At that point I get a message that says "Access Denied with an "ok" button. I click OK, then it proceeds to uninstall what was installed. Am I not supposed to have this search function or is there a work around? Note: I have Google desktop search installed-could that be a conflict? If so-how do I remove it when it doesn't show up in Add/Remove Programs? LV I am experiencing ...

upgrading Action Pack CRM to 1.2
I recieved Microsoft CRM 1.0 with my Microsoft Action Pack subscription. Does anyone know if the 1.2 update will be available for download. Will we recieve a update in later Action Pack releases. Can Action pack subscribers get access to CustomerSource and download the update. Does anyone know a way to get the update legally. I would like to begin testing 1.2 now. Thanks I spoke with microsoft today and he mentioned that Ver 1.2 will be available in the Action Pack update late January. Len >-----Original Message----- >I recieved Microsoft CRM 1.0 with my Microsoft Ac...

Managing contacts #2
In an organisation with about 4 large departments, what would be the best way to manage business contacts? (Moving to exchange/outlook 2003 and all the contacts have been exported from previous versions of outlook into CSV files.) The most logical option seems to try and get all the external contacts into GAL instead of each person in the department maintaining his/her own list in Outlook. Which brings us to the question of HOW to import a large number of external contacts from a CSV file into GAL. (or would a shared address book be a better solution?) Thanks in advance Francois ...

Workbook Protection #2
I have created a workbook with 5 different worksheets. In each worksheet I have hidden certain rows. I want to be able to protect the hidden rows so that they can not be unhidden. Is there a way to protect the workbook so the rows are hidden without doing each sheet individually? I tried to use the Protect Workbook feature but when I tested it did not work. any help would be appreciated. Thanks, John Not manually. You could have a macro that cycles through the worksheet and protects each of them, though. Option Explicit Sub protectAll() Dim wks As Worksheet For Eac...

Distribution group problem #2
Hello, I'm new to exchange administration. Anyway I would like to create a distribution group and add a security group in it. How can I do it? I've added a distribution group and then added a security group to it as a member. I gave it a mail address from exchange. But this is not working. What can I do? How can I create a mail-enabled security group? Thank you Erman To create a mail-enabled Security Group: Create new group in ADUC (AD Users & Computers) by right-clicking the OU or container you want to create it in - New - Group. In the Group dialog box select "Security&q...

updating pivot table #2
I have pivot tables that I update weekly with new data. Unfortunately, the prior week's options are included in the updated drop down lists. The old data is not included in the calculations so it doesn't affect the report in that regard but although I only have 18 weeks of data in the source worksheet, the drop-down lists show the 32 weeks I have been running the report as options. It is confusing to users of the report. There's information here on clearing old items in a pivot table: http://www.contextures.com/xlPivot04.html Gibran wrote: > I have pivot table...

Gift Receipts #2
I already know about the way to print gift receipts on the 2nd printer but that isn't going to work some merchants as they use the second printer in Store Ops to print full page receipts for customers with accounts. I was at Target and saw an interesting way that they handle their gift receipts. You get one, long receipt and at the bottom is a gift receipt. You can cut the receipt along the dotted line and then you have a gift receipt as well as the detailed receipt. Would it be possible to create a receipt format for RMS that does this? Yes, it would be similar to the Credit C...

Excel Form #2
I would like to create an online form in Excel which when filled out can be sent back to me via email? If my email address is Joebloggs@Hello.com how would I create a hyerlink to attach the form that is being filled out to the address? When I use mailto:joe.bloggs@hello.com a new email message appears but that doesn't send my fomr? Help me please!! Jacqui Button England Jacqui, Try ActiveWorkbook.SendMail Recipients:=jacqui.button@talk21.com HTH Henry "Jacqui button" <jacqui.button@talk21.com> wrote in message news:021701c39686$8c80a110$a501280a@phx.gbl... &...

inbound email body blank #2
thank you for the reply. my original post describes the fix as changing the fonts in the display settings. that's not clear, sorry, by changing the font size in the display setting the system does re-install the fonts. additionally, another item i did not specify is that this issue consistently occurs once a year. it does occur on win2000 as well. what is the fix so that it does not reoccur? any ideas? thanks again. paul . Reply (E-mail) Forward (E-mail) Subject: Re: inbound email body blank From: "Tamir Khason" <tamir-NOSPAM@tcon-NOSPAM.co.il> Sent: ...

Error message on closing Outlook #2
I am getting the following error message when closing Outlook: The instruction at "0x77f83907" referenced memory at "0x009a4d4c". The memory could not be "written". Click on OK to terminate the program I have tried the Microsft Online help but it wouldn't accept my product number so I wondered if anyone else had encountered such an error. I would like to know what it's doing! cheers ...

V 2.0 issue
When creating new items "on the fly" while receiving, the new item does not default to the sales tax that has been defined as default. Also, a few extra fields ( perhaps Department, MPQ, tax ) to give the item enough data to be usable, or a report that would show all items added through this technique so the items data can be reviewed and filled out in the office after the PO is committed. Also, make as many of these processes "mouseless" as possible, so that we can receive and enter items and jump through all fields quickly and smoothly with the Tab key and enteri...

All Day Calendar Events appear as 2 days
Hello: I have starting to feel the effects of DST... I have a public calendar. I have a series of all day events. Just after March 11th these appointments are showing as 2 day events. I applied the patch to most of my workstations, but will not apply the Exchange patch until this weekend. I am a little confused by this behavior. Does anyone have any suggestions? Harrison Midkiff an all day event is something scheduled for 24 hours, when they get off by an hour, they overflow to the next day, which is what happened, you need to patch the exchange server then run tzmove to fix ...

Exporting from Netscape 7.2 to Outlook 2003. Read previous posts.
I have been using Netscape 7.2 and I'm new to Outlook 2003. My plan was to install Netscape Communicator 4.79, transfer my emails from Netscape 7.2 to Communicator 4.79, import from Communicator 4.79 to Outlook Express, and export from OE to Outlook 2003. Now that I've installed Communicator 4.79, how do I transfer the emails from Netscape 7.2 to Communicator 4.79? Thanks! ...

Excel help #2
Hi - I'm pretty familiar with most stuff in excel and I'd say I'm an intermediate user. I would like to learn how to do vba in excel. Does anyone know of any online help or tutorials that would teach me? If possible, I would like interactive suggestions. Thanks in advance. Newtechie David McRitchie's "Getting Started". Note links to other sites at the boittom of the page. http://www.mvps.org/dmcritchie/excel/getstarted.htm VBA Tutorial from Microsoft. http://support.microsoft.com/support/excel/content/vba101/default.asp There are many more, but these sho...

MSPOS 2 Receipt modifying
Hi everyone. I have a couple of issues that I would like some help on. I have tried to modify directly the 40 col receipt xml file, for example the code page and paper width,but I wish to do others however when I add the new receipt format into manager and open the editor there, my changes are not shown as actioned. If I then add the receipt to my till the changes are also not actioned - is there a way or technique to do, or not to do these modifications? Also I am using an Epson Tm-III printer on LPT1 and the number of columns it is printing is causing the print to line wrap. I have set the p...

Outlook settings #2
Want to take full back-up of all outlook settings e.g. Rules, Signature, Identity ...

Printing ranges #2
I have three different ranges ie A37:M50,A98:M111,A152:M160 and would like them to print on one page - is this possible? Thanks T Hi see: http://www.rondebruin.nl/print.htm#non-contiguous -- Regards Frank Kabel Frankfurt, Germany "Tim" <anonymous@discussions.microsoft.com> schrieb im Newsbeitrag news:12de801c4435f$8e0ff0e0$a401280a@phx.gbl... > I have three different ranges ie > A37:M50,A98:M111,A152:M160 and would like them to print > on one page - is this possible? > > Thanks T Take a look here: http://groups.google.com/groups?oi=djq&ic=1&s...

Lost all inbox and contacts etc when removed server #2
I found the outlook.ost file. Can I reimpost this to Outlook? Can I somehow set it or use it as the "personal data files" that the outlook dialog box requested? I dont get why I was able to access the contacts emails etc after I disconnected the exchange server BUT only after I removed the exchange server did it all disappear. Not sure how I was meant to continue this thread so I copied the previous question, comment and listed it as a new post -- hope this it ok protocol. Also someone else had recommended that I re-engage the server but it is neither listed nor frank...

arrow keys for child window of dialog box #2
Hi, I have created a dialog box with MFC. I have created an opengl window as a child to the dialog box. on the window I am drawing using opengl. now I want to update my drawing if the arrow keys are pressed. How should I do it . I am new to MFC. Thanks and Regards. Hi, Handle WM_KEYDOWN message (let the wizard do it for you as you are new to MFC). Then you can put some kode like so: void CMyWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { switch (nChar) { case VK_LEFT: YourUpdateCode1(); break; case VK_UP: YourUpdateCode2(); break; case VK_RIGHT: YourUpdateCode3...

PS POS 2.0
Does POS 2.0 come with gift card functionality or is it only the RMS version of POS? The screenshots I have seen show a gift card tender type, but I havent been able to try a demo of it yet to see if it comes built in now or now. Thanks, --Mike It's there as "description" for a tender type. No extra function around it that I'm aware of. -- John M. "DomitianX" <DomitianX@discussions.microsoft.com> wrote in message news:5D75C630-2C67-4FAA-9819-063C2A0A40D3@microsoft.com... > Does POS 2.0 come with gift card functionality or is it only the RMS >...