我正在玩一些套接字,线程和互斥.我的问题涉及线程和互斥体:
int ConnectionHandler::addNewSocket(){
this->connectionList_mutex.lock();
std::cout << "test1" << std::endl;
this->connectionList_mutex.unlock();
return 0;
}
int ConnectionHandler::main(){
while(true){
this->connectionList_mutex.lock();
std::cout << "test2" << std::endl;
this->connectionList_mutex.unlock();
}
}`
Run Code Online (Sandbox Code Playgroud)
main函数在一个线程中运行,而addNewSocket由另一个线程调用.问题是,当addNewSocket被调用一次(由第二个线程)时,线程1(main)的下一个解锁将失败并出现奇怪的"信号SIGABRT".我现在已经工作了两天,但遗憾的是我无法修复它.我希望你能帮助我.
编辑:ConnectionHandler是一个类,具有connectionList_mutex作为成员.
编辑:有时我也会收到此错误:"断言失败:(ec == 0),函数解锁,文件/SourceCache/libcxx/libcxx-65.1/src/mutex.cpp,第44行." 但它随机发生.
编辑:这是整个类(减少到最小,应该在某种程度上独立于上下文,但是当我在连接客户端之后立即崩溃时崩溃,并且如果我在开始之后立即执行它会起作用:
class ConnectionHandler{
public:
ConnectionHandler();
int addNewSocket();
private:
int main();
static void start(void * pThis);
std::mutex connectionList_mutex;
};
ConnectionHandler::ConnectionHandler(){
std::thread t(&this->start, this);
t.detach();
}
void ConnectionHandler::start(void * pThis){
ConnectionHandler *handlerThis;
handlerThis = (ConnectionHandler *)pThis;
handlerThis->main();
}
int ConnectionHandler::addNewSocket(){
this->connectionList_mutex.lock();
std::cout << "test1" << std::endl;
this->connectionList_mutex.unlock();
return 0;
}
int …Run Code Online (Sandbox Code Playgroud)