Link to home
Start Free TrialLog in
Avatar of jhanson040697
jhanson040697

asked on

Using CAsyncSocket from multiple threads

I am trying to use CAsyncSocket to create two separate sockets in two separate threads. One is being created in the main application thread, the other in a worker thread. I have no problems creating the socket in the main thread, but when I try to call Create() in the worker thread, the call dies inside CAsyncSocket. I traced through the MFC code and it seems there are some thread local data structures which store the socket handles used by CAsyncSocket. These structures appear not to have been intialized for my worker thread as the pointers to them are NULL. After some further searching I found that these data structures are initialized by AfxSocketInit(). I found that if I call AfxSocketInit() from within my worker thread, I can create sockets within it. This only workes if I remove the AfxSocketInit() from my main thread as MFC doesn't let you Initialize sockets twice. This prevents me from being able to create sockets in the main thread.

I find it hard to believe that there is no way to create CAsyncSockets in multiple threads and I have seen nothing in the documentation that would indicate that this is the case. Therefore I assume I must be doing something wrong. Is there anything I need to do to prepare a thread to create a socket? Would it help if I used a user interface thread instead of a worker thread? Is there some sort of limitation on using CAsyncSocket with multiple threads? Any help would be appreciated....
ASKER CERTIFIED SOLUTION
Avatar of JohnnyXia
JohnnyXia

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