【发布时间】:2012-12-13 16:16:09
【问题描述】:
我正在玩一些套接字、线程和互斥锁。我的问题涉及线程和互斥锁:
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();
}
}`
main 函数在一个线程中运行,而 addNewSocket 被另一个线程调用。问题是,当 addNewSocket 被调用一次(由第二个线程)时,线程 1(主)的下一次解锁将失败并出现一个奇怪的“信号 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 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();
}
}
【问题讨论】:
-
为什么要标记标准?你的互斥锁是 std::mutex 还是什么?
-
是的,互斥体和线程都是c++11 std
-
好吧,也许我很愚蠢,但现在(我编写了一个小代码)有效,我只需要弄清楚为什么它在我的真实程序的上下文中不起作用
-
它可能对您的问题没有帮助,但应该考虑使用 RAII 包装器(
lock_guard或unique_lock)来锁定互斥锁,而不是手动锁定和解锁。这样,如果块提前退出或抛出异常,它就不会永远锁定。 -
@sh4kesbeer:它们是标准的 C++11 类,因此它们应该可以移植到任何你可以使用
std::mutex本身的地方。
标签: c++ xcode multithreading mutex std