Is CAsyncSocket thread-safe when used with one thread for reading and one for writing?

2025-10-13T07:18:57.3433333+00:00

Hello,

We've been using CAsyncSocket in a multithreaded setup for some time — one thread dedicated to reading, and one handling writing.

However, we've encountered an issue where the PumpMessage method occasionally stops receiving SELECT messages, resulting in a deadlock.

Our current approach involves detaching (on the creation thread) and reattaching the socket in each thread sequentially, using a locking mechanism to ensure synchronization.

According to the documentation for WSAAsyncSelect (which is called during Attach), issuing a new WSAAsyncSelect cancels any previous WSAAsyncSelect or WSAEventSelect for the same socket.

What’s unclear is whether this cancellation is thread-local or global. This ambiguity has led us to question whether using CAsyncSocket across multiple threads — even with proper locking — is truly supported or safe.

Thank you for your help, Best regards, Alexandre

Windows development | Windows API - Win32
{count} votes

1 answer

Sort by: Most helpful
  1. Linhnguyen Hanoi 0 Reputation points
    2025-10-15T03:22:31.4633333+00:00

    Is CAsyncSocket thread-safe when used with one thread for reading and one for writing?

    No, CAsyncSocket is not thread-safe when used with one thread for reading and one for writing.

    CAsyncSocket::Create is not thread-safe. If you are calling it in a multi-threaded environment where it could be invoked simultaneously by different threads, be sure to protect each call with a mutex or other synchronization lock. I suggest you need to use CCriticalSection or CMutex.

    Of course, I would recommend you use CSocket instead of CAsyncSocket. A CSocket object also provides blocking, the blocking read simplifies the read thread's logic.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.