PDA

View Full Version : Need help/suggestion with multithreadding and sockets



Floppe
18th March 2009, 07:33
Hello,

I'm trying to build a class MySocket which I think would be best if it starts a thread for incoming data and stores that data in a buffer which should be shared with the parent thread. All other functions are outside this worker thread.

Basic example would be a ping function. This function sends a ping to the server and waits for an answer and timeouts if no answer is received. This answer is parsed from the buffer. So in short, incoming data should be feed to the buffer while this function waits (which could take 10 seconds over laggish GPRS).

How should I build this?
Or are there any better ideas to accomplish this?
If main thread declares MySocket and connects to server, can worker threads use this same connection?

// Floppe

wysota
20th March 2009, 08:51
You don't need a worker thread to handle a socket. Qt uses sockets in asynchronous way - you will be notified when there is anything to read from the socket. Simply connect to appropriate signals and you're done.

Floppe
20th March 2009, 12:03
So I also tought. However, it seems like the notify will come in after a lengty function has finished. So the ping function did never got an answer or maybe I did need to run something like processEvents. I got it to work with threads though.

Thanks
// Floppe

wysota
20th March 2009, 14:24
So I also tought. However, it seems like the notify will come in after a lengty function has finished.
Yes, that's correct. You need to let the event loop process events from time to time. You should do that anyway to prevent your GUI from freezing.