I've created a basic multithreaded TCP server and I would like to send data to all connected clients. I've connected server class' signal writing(QByteArray)
to socket thread's slot writeToSocket(QByteArray)
, but when I try to write to that socket by emitting signal mentioned above, I get segmentation fault. It's just like I can't access to any socket object's (which is thread's property) method.
My simplified code:
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");
}
Then, in thread's source file:
void ConnectionThread::writeToSocket(QByteArray data) // a slot
{
this->socket->write(data);
}
Just an idea. I maybe wrong.
New/delete is not threadsafe in C++. Not sure if this is still true for C++0x. I encountered this problem with pthreads.
If you use memory allocated with new it can throw segmentation fault even the syntax seems correct. Try to allocate it in the thread/threaded function if possible.
Hope this will help you.