2012-04-04 75 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遇到了這個問題。

如果你使用新分配的內存,它可能會引發分段錯誤,即使語法看起來正確。如果可能的話,嘗試在線程/線程函數中分配它。

希望這會幫助你。