当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Qt socket write segmentation fault

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: