2012-04-04 102 views
1

我创建了一个基本的多线程TCP服务器,我想将数据发送给所有连接的客户端。我已将服务器类'signal writing(QByteArray)连接到套接字线程的插槽writeToSocket(QByteArray),但是当我尝试通过发送上述信号写入该套接字时,出现分段错误。这就像我不能访问任何套接字对象(这是线程的属性)方法。Qt套接字写入分段错误

我的简化代码:

void MyServer::incomingConnection(int handle) 
{ 
ConnectionThread *thread = new ConnectionThread(handle, this); 
connect(this, SIGNAL(writing(QByteArray)), thread, SLOT(writeToSocket(QByteArray))); 
// Some more code necessary for thread to work 
} 

void RoleNetServer::WriteToAll(QByteArray data) 
{ 
    emit writing("test"); 
} 

然后,在线程的源文件:

void ConnectionThread::writeToSocket(QByteArray data) // a slot 
{ 
    this->socket->write(data); 
} 
+0

尝试通过仅运行1个客户端来排除线程问题。这可能只是因为你传递的数据长度比缓冲区长。如果可以,请发布[SSCCE](http://sscce.org/)。回溯也会有所帮助。 – je4d 2012-04-04 21:26:32

回答

0

只是一个想法。我可能错了。

在C++中,新/删除不是线程安全的。不知道这是否仍然适用于C++ 0x。我用pthreads遇到了这个问题。

如果你使用新分配的内存,它可能会引发分段错误,即使语法看起来正确。如果可能的话,尝试在线程/线程函数中分配它。

希望这会帮助你。