             if connections.keys.count >= maxConnections { waitForSpace() }
             // the maximum number of connections has been created, even after attempting to clear out closed connections
             if connections.keys.count >= maxConnections { throw Error.maxConnectionsReached(max: maxConnections) }
-            connection = try connectionFactory()
+            let c = try connectionFactory()
+            connections[threadId] = c
+            connection = c
         }
 
         guard let c = connection else { throw Error.lockFailure }
-        connections[ThreadConnectionPool.threadId] = c
         return c
     }
 

import Core

/**
    Responsible for maintaing of pool
    of connections, one for each thread.
 
    Uses a Driver to make new connections.
*/
public final class ThreadConnectionPool {
    public enum Error: Swift.Error {
        case lockFailure
        case maxConnectionsReached(max: Int)
        // to allow extensibility w/o breaking apis
        case open(Swift.Error)
    }

    public typealias ConnectionFactory = () throws -> Connection

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


    private var connections: [pthread_t: Connection]

    /**
        Initializes a thread pool with a connectionFactory intended to construct
        new connections when appropriate and an Integer defining the maximum 
        number of connections the pool is allowed to make
    */
    public init(connectionFactory: @escaping ConnectionFactory, maxConnections: Int) {
        self.connectionFactory = connectionFactory
        self.maxConnections = maxConnections
