Browse Source

fixed possible race condition

AlexVinS 8 years ago
parent
commit
09df2dcfbb
3 changed files with 19 additions and 9 deletions
  1. 4 2
      client/CMT.cpp
  2. 13 6
      client/Client.cpp
  3. 2 1
      client/Client.h

+ 4 - 2
client/CMT.cpp

@@ -1355,8 +1355,10 @@ void startGame(StartInfo * options, CConnection *serv/* = nullptr*/)
 			client->loadGame(fname,vm.count("loadserver"),vm.count("loadhumanplayerindices") ? vm["loadhumanplayerindices"].as<std::vector<int>>() : std::vector<int>(),vm.count("loadnumplayers") ? vm["loadnumplayers"].as<int>() : 1,vm["loadplayer"].as<int>(),vm.count("loadserverip") ? vm["loadserverip"].as<std::string>() : "", vm.count("loadserverport") ? vm["loadserverport"].as<ui16>() : CServerHandler::getDefaultPort());
 		break;
 	}
-
-	client->connectionHandler = new boost::thread(&CClient::run, client);
+	{
+		TLockGuard _(client->connectionHandlerMutex);
+		client->connectionHandler = make_unique<boost::thread>(&CClient::run, client);
+	}
 }
 
 void endGame()

+ 13 - 6
client/Client.cpp

@@ -113,7 +113,10 @@ void CClient::init()
 {
 	waitingRequest.clear();
 	hotSeat = false;
-	connectionHandler = nullptr;
+	{
+		TLockGuard _(connectionHandlerMutex);
+		connectionHandler.reset();
+	}
 	pathInfo = nullptr;
 	applier = new CApplier<CBaseForCLApply>;
 	registerTypesClientPacks1(*applier);
@@ -710,15 +713,19 @@ void CClient::stopConnection()
 		}
 	}
 
-	if(connectionHandler)//end connection handler
 	{
-		if(connectionHandler->get_id() != boost::this_thread::get_id())
-			connectionHandler->join();
+		TLockGuard _(connectionHandlerMutex);
+		if(connectionHandler)//end connection handler
+		{
+			if(connectionHandler->get_id() != boost::this_thread::get_id())
+				connectionHandler->join();
 
-		logNetwork->infoStream() << "Connection handler thread joined";
-		vstd::clear_pointer(connectionHandler);
+			logNetwork->infoStream() << "Connection handler thread joined";
+			connectionHandler.reset();
+		}
 	}
 
+
 	if (serv) //and delete connection
 	{
 		serv->close();

+ 2 - 1
client/Client.h

@@ -172,7 +172,8 @@ public:
 	const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
 
 	bool terminate;	// tell to terminate
-	boost::thread *connectionHandler; //thread running run() method
+	std::unique_ptr<boost::thread> connectionHandler; //thread running run() method
+	boost::mutex connectionHandlerMutex;
 
 	//////////////////////////////////////////////////////////////////////////
 	virtual PlayerColor getLocalPlayer() const override;