我在嘗試創建多線程服務器時遇到了一些問題。一切工作正常,直到我需要從服務器中刪除客戶端。調用加入時Boost :: Thread訪問衝突
服務器運行在它自己的線程中,然後每個客戶端都有它自己的線程。
我對所有線程都使用boost :: thread。當我需要停止客戶端我叫
void StopClient()
{
assert(mThread);
mStopMutex.lock();
mStopRequested = true;
mStopMutex.unlock();
shutdown(mSocket,2);
mThread->join();
}
添加斷點行
shutdown(mSocket,2);
我可以看到mThread不存在!這是否意味着線程已經退出?你是否總是需要爲boost :: thread調用join()?
如果我允許代碼運行,則會出現訪問衝突錯誤。
更新
ServerThread
void StartServer()
{
assert(!mListenThread);
mListenThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&ServerThread::Listen, this)));
mUpdateThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&ServerThread::Update, this)));
}
void StopServer()
{
assert(mListenThread);
mStopRequested = true;
mMutex.lock();
for(int i = 0; i < mClients.size(); i++)
mClients[i]->StopClient();
mMutex.unlock();
mListenThread->join();
}
void Listen()
{
while (!mStopRequested)
{
std::cout << "Waiting for connection" << std::endl;
if(mClientSocket = accept(mServerSocket, (sockaddr*) &mServerAddr, &addrlen))
{
mMutex.lock();
if(mClients.size() > 0)
{
for(int i = 0; i < mClients.size(); i++)
{
if(mClients[i]->getClientSocket() != mClientSocket)
{
ClientThread newClient;
newClient.Initialise(mClientSocket);
mClients.push_back(&newClient);
mClients[mClients.size()-1]->StartClient();
break;
}
}
}
else
{
ClientThread newClient;
newClient.Initialise(mClientSocket);
mClients.push_back(&newClient);
mClients[mClients.size()-1]->StartClient();
}
mMutex.unlock();
}
}
}
void Update()
{
while (!mStopRequested)
{
mMutex.lock();
std::cout << "::::Server is updating!::::" << mClients.size() << std::endl;
for(int i = 0; i< mClients.size(); i++)
{
if(!mClients[i]->IsActive())
{
mClients[i]->StopClient();
mClients.erase(mClients.begin() + i);
}
}
mMutex.unlock();
}
}
ClientThread
void StartClient()
{
assert(!mThread);
mThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&ClientThread::Update, this)));
}
void Update()
{
bool stopRequested;
do
{
mStopMutex.lock();
stopRequested = mStopRequested;
mStopMutex.unlock();
std::cout << "lol" << std::endl;
if(mTimeOut < 1000)
{
mTimeOut++;
}
else
{
mActive = false;
}
boost::this_thread::interruption_point();
}
while(!stopRequested);
}
您需要向我們展示更多的代碼。 「mThread」在哪裏設置,以及什麼值?它還用在哪裏? –
「mThread不存在」是什麼意思?它是NULL還是它指向一個已刪除的對象? – mmmmmmmm
感謝您的回覆。我已更新以顯示更多代碼! @Rüdiger它只是指向一個被刪除的對象。 – kiwijus