     /// - Parameter from: An UnsafeRawPointer to the sequence of bytes to be written to the socket.
     /// - Parameter length: The number of bytes to write to the socket.
     public func write(from bytes: UnsafeRawPointer, length: Int) {
+        writeInProgress = true
+        defer {
+            writeInProgress = false // needs to be unset before calling close() as it is part of the guard in close()
+            if preparingToClose {
+                close()
+            }
+        }
+
+        // Set writeInProgress flag to true before the guard below to avoid another thread
+        // invoking close() in between us clearing the guard and setting the flag.
         guard isOpen && socket.socketfd > -1 else {
             Log.warning("IncomingSocketHandler write() called after socket \(socket.socketfd) closed")
+            preparingToClose = true // flag the function defer clause to cleanup if needed
             return
         }
 

                }
            }
            catch let error {
                writeInProgress = false
                if let error = error as? Socket.Error, error.errorCode == Int32(Socket.SOCKET_ERR_CONNECTION_RESET) {
                    Log.debug("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).")
                } else {

            let written: Int
            
            if  writeBuffer.length == 0 {
                written = try socket.write(from: bytes, bufSize: length)
            }
            else {
                written = 0
