Link to home
Start Free TrialLog in
Avatar of kai028
kai028

asked on

Inconsistency between Debug and Release configurations when using serial port under Windows with C++

I have a program that uses the serial port with Windows XP (it is written in Visual C++ 4 - yes, 4!). It has a separate thread for receiving data from the port.

The problem is that, while everything works fine in both Debug and Release versions, there is a problem with exiting the application. When I exit from the Release version, and try to restart it, I get a message saying that the port cannot be opened. Task Manager says the application still has a process running. This doesn't happen with the Debug version. I am using CloseHandle, which succeeds, and I am setting the port handle to NULL afterwards.

This is the first time I'm writing a multiple-thread application for Windows, so I'm a bit lost. Why don't ALL my threads exit when I exit my program under Release configuration?

Does anybody know what I can do to make the program work under Release the same way it does under Debug? I'd really appreciate the help. Thanks!
Avatar of AlexFM
AlexFM

You need to stop properly all running threads, and exit main application thread. What is your application type (Console, Windows application)?
Quick and dirty solution is using CRT exit() function.
Avatar of kai028

ASKER

Thanks for the comment, Alex. This is a Windows application, not a console app. I'm not actually using MFC - I didn't know how to use the serial port under Windows, so I found an old Microsoft port demonstration program, written in the straight old API, to base my app on.

How do I "properly stop all running threads"? I thought setting the thread ID to 0 would do that.
First, try TerminateThread for every running thread - this must solve the problem of exiting application. However, this is not 100% correct solution.
To stop thread properly, you need to ask thread to exit, and wait while thread actually exits. This is done using event associated with thread - let's call it Stop event. THread periodically tests Stop event state and exists immediately when it is signaled. When main thread needs to stop worker thread, it sets Stop event and waits for thread handle.

ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kai028

ASKER

Thanks, Alex. I'll go over your earlier answer and see if I can use the info to fix my program. BTW, I am using SendMessage to send stuff from my serial port thread back to the main thread. I suppose this isn't really the best way to alert the main thread that new data is available - I should probably use some kind of semaphore, but I have no experience doing that. Oh, well; I'm going to have to learn sometime!