Accept and Multi-Threading problem!!!

hi folks,

    I am building a server application using CSocket class and threads. In my server app, I create a child thread (worker thread) to handle connection (Accept()) and network I/O (infinite loop). I also create a  exit message handler to closes all network connections. Whenever I click the exit button on my server app, my program crashed. Why?? Any solution??

stephen
 
stephenkongAsked:
Who is Participating?
 
jonaleeCommented:
Please do not use CSocket::Close() directly. Use Shutdown(2) first. Then overide the CAsyncSocket::OnClose(int). In that function, call Close() after CAsyncSocket::Close() is called.

Also, if the coding you give out is in the Thread, please use PostThreadMessage(WM_QUIT,0,0L)


0
 
jkrCommented:
Do you synchronize the access to the CSockets between the threads and the message handler?
0
 
yoffeCommented:
Adding to jkr's response, is the worker thread accessing any objects that are created by another therad (stack or heap).   If so, when your primary (MH) thread dies and destroys those objects, access violation...game over.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
shaigCommented:
While the win32 api is thread safe, MFC isn't. You should sinchronize all access to MFC objects yourself.
0
 
jkrCommented:
>>While the win32 api is thread safe...
shaig, i wish it was! ;-)
(just try 2 threads accessing one GDI object without synchronization...)
0
 
koskiaCommented:
My program Crash answer !??

add some code, maybe this will help ?!
0
 
shaigCommented:
Using handles?  Well if you say so i'll take your word for it. When you think you saw it all, Microsoft come and...
0
 
jkrCommented:
shaig - it is so. Somewhere deep in the docs they state that the GDI isn't sync'ed due to performance issues ;-)
0
 
stephenkongAuthor Commented:
hello folks,

   My worker thread was executing CSocket::Accept() while I was pressing the Exit button.

   In the 'Exit' message handler:
{
// This variable is useless since worker thread was stuck in
// CSocket::Accept()
   m_bIsFinished = TRUE;  // bool variable to break the infinite
                          // loop inside the worker thread
   Sleep(300);    
   sock.Close();
   PostQuitMessage (0);
}
0
 
fasterCommented:
When the main thread close the socket of worker thread, if the worker thread is still using the thread and error handling is not carefully done, this might happen.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.