     }
     
     internal func connection() throws -> Connection {
-        guard let existing = connections[ThreadConnectionPool.threadId] else { return try makeNewConnection() }
+        // MUST capture threadID OUTSIDE of lock to ensure appropriate thread id is received
+        let threadId = ThreadConnectionPool.threadId
+
+        var connection: Connection?
+        connectionsLock.locked {
+            connection = connections[threadId]
+        }
+
+        guard let existing = connection else { return try makeNewConnection() }
         return existing
     }
 
     private func makeNewConnection() throws -> Connection {
+        // MUST capture threadID OUTSIDE of lock to ensure appropriate thread id is received
+        let threadId = ThreadConnectionPool.threadId
+
         var connection: Connection?
-
         try connectionsLock.locked {
             // Attempt to make space if possible
             if connections.keys.count >= maxConnections { clearClosedConnections() }


    private var connections: [pthread_t: Connection]

    public init(connectionFactory: @escaping ConnectionFactory, maxConnections: Int) {
        self.connectionFactory = connectionFactory
        self.maxConnections = maxConnections

import Core

/**
    Responsible for maintaing a pool
    of connections, one for each thread.
*/
public final class ThreadConnectionPool {

    /**
        Thread Pool Errors
    */
    public enum Error: Swift.Error {
        /**
            Something in our internal lock mechanism has unexpectedly failed 
            ... should never see this except for more widespread system 
            dispatch errors
        */
        case lockFailure

        /**
            The maximum number of active connections has been reached and the pool
            is no longer capable of creating new ones.
        */
        case maxConnectionsReached(max: Int)

        /**
            This is here to allow extensibility w/o breaking apis, it is not currently
            used, but should be accounted for by end user if they are handling the 
            error
        */
        case open(Swift.Error)
    }

    /**
        The constructor used by the factory to create new connections
    */
    public typealias ConnectionFactory = () throws -> Connection


    private static var threadId: pthread_t {
        // must run every time, do not assign
