From 7e0df026a7ffc410ee1b679590025fa68b6af133 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Remko=20Tron=C3=A7on?= <git@el-tramo.be>
Date: Fri, 3 Feb 2012 19:58:58 +0100
Subject: Close socket immediately after last pending write finished.

This should fix a hang on disconnect().

diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp
index 534ebdb..7b997b4 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -75,6 +75,7 @@ void BoostConnection::disconnect() {
 	// Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep.
 	// See e.g. http://bugs.python.org/issue7401
 	// We therefore wait until any pending write finishes, which hopefully should fix our hang on exit during close().
+	boost::lock_guard<boost::mutex> lock(writeMutex_);
 	if (writing_) {
 		closeSocketAfterNextWrite_ = true;
 	} else {
@@ -87,9 +88,6 @@ void BoostConnection::write(const SafeByteArray& data) {
 	if (!writing_) {
 		writing_ = true;
 		doWrite(data);
-		if (closeSocketAfterNextWrite_) {
-			socket_.close();
-		}
 	}
 	else {
 		append(writeQueue_, data);
@@ -149,6 +147,9 @@ void BoostConnection::handleDataWritten(const boost::system::error_code& error)
 		boost::lock_guard<boost::mutex> lock(writeMutex_);
 		if (writeQueue_.empty()) {
 			writing_ = false;
+			if (closeSocketAfterNextWrite_) {
+				socket_.close();
+			}
 		}
 		else {
 			doWrite(writeQueue_);
-- 
cgit v0.10.2-6-g49f6