gpt4 book ai didi

c++ - Boost::调用连接时线程访问冲突

转载 作者:行者123 更新时间:2023-11-28 08:18:00 26 4
gpt4 key购买 nike

我在尝试创建多线程服务器时遇到了一些问题。一切正常,直到我需要从服务器中删除客户端。

服务器在它自己的线程中运行,然后每个客户端也有它自己的线程。

我正在为所有线程使用 boost::thread。当我需要停止客户端时,我会调用

void StopClient()
{
assert(mThread);

mStopMutex.lock();
mStopRequested = true;
mStopMutex.unlock();

shutdown(mSocket,2);

mThread->join();
}

在行中添加断点

shutdown(mSocket,2);

我可以看到 mThread 不存在!这是否意味着线程已经退出?您是否总是需要为 boost::thread 调用 join()?

如果我允许代码运行,我会收到访问冲突错误。

更新

服务器线程

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();

}
}

客户端线程

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);
}

最佳答案

            ClientThread newClient;
newClient.Initialise(mClientSocket);
mClients.push_back(&newClient);

这会在堆栈上创建一个局部变量,并将它的地址放入您的 mClients 列表中。然后作用域结束,局部变量也结束。这使您的列表 mClients 指向不再存在的内容。

关于c++ - Boost::调用连接时线程访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com