我正在尝试使用一些套接字、线程和互斥锁。我的问题涉及线程和互斥锁:
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();
}
}`
主要功能在一个线程中运行,而addNewSocket是由另一个线程调用的。 问题在于,当addNewSocket被第二个线程调用一次时,主线程下一次解锁将失败,并出现奇怪的“信号SIGABRT”。 我已经花了两天时间来解决这个问题,但可惜没有成功。 我希望你能帮助我。
编辑:ConnectionHandler是一个类,其中包含connectionList_mutex作为成员。
编辑:有时我还会收到此错误:“Assertion failed: (ec == 0), function unlock, file / SourceCache / libcxx / libcxx-65.1 / src / mutex.cpp,line 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 ConnectionHandler::main(){
while(true){
this->connectionList_mutex.lock();
std::cout << "test2" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
this->connectionList_mutex.unlock();
}
}
lock_guard
或unique_lock
)来锁定互斥量,而不是手动锁定和解锁。这样,如果块提前退出或抛出异常,它就不会被永久锁定。 - Mike Seymourstd::mutex
的任何地方进行移植。 - Mike Seymour