PDA

View Full Version : Multithreading issue



ayanda83
17th November 2013, 14:06
hi everyone, i'm creating a tcp/ip server for a chat app. i want to use the threadpool to dedicate threads to connected clients but because QRunnable does not support signals and slots i have no clue how to implement the server. the portion of the code that needs to listen to the incoming connections is in the run function of my QRunnable object (i.e. myTask). The problem comes when i have to connect the "ReadyRead()" signal to a slot that is reponsible for reading data from the socket (Mind you, this slot runs on a separaten thread from the code in the "run" function of QRunnable). Because of this if i try connecting signals and slots inside the run function my server crashes when a client tries connecting to it. below is my run function without the connect function to connect the signals and slots. please assist with this if you knows how to solve this problem please share.

void MyTask::run()
{
if(!socketDescriptor) return;
QTcpSocket sock;
sock.setSocketDescriptor(socketDescriptor);

sock.write("Hello Client");
sock.flush();
sock.waitForBytesWritten(5000);
sock.close();
}

anda_skoa
18th November 2013, 11:07
Aside from the obvious question why you want to do threading here at all, are you sure you want to limit the number of clients to the number of threads in the pool?

Anyway, your run() function is very similar in context to main(), so, just like in main(), create a receiver object, connect to its slots and then either start the thread's event loop.
Or use the synchronous approach and call waitForReadyRead().

But you should really rethink the need to make this so complicated. Unless you are doing heavy processing of data sent from or to the client there is no need for threads. Which in the case of a chat client doesn't sound very likely.

Cheers,
_