Fix some problems calling disconnect before exiting application.

First change prevents "Exception in thread Thread-17 (most likely raised during interpreter shutdown)" type errors by ensuring the connection thread has exited before returning from disconnect.

Second change prevent a race between _on_error and disconnect assigning to the need_reconnect flag (which, when combined with the above change, can cause disconnect to hang).