views:

127

answers:

3

I have a QThread that reads from a socket and sends a signal (QT signal) when there are any data available. This would be easy with blocking read(2), but i need to be able to stop the thread from outside without waiting for too long.

If I were using pthread I would use pselect and pthread_kill(thread_id, some_signal), but QThread doesn't seem to have any similar methods. And adding a dependcy on pthread to this project doesn't seem to elegant.

I also don't want to use the other ugly methods like constantly trying to read from the socket with some relatively small timeout.

Edit: The sockets are not TCP, but bluetooth L2CAP.

A: 

You can send a signal to the terminate() slot of your QThread. This will stop your thread according to OS scheduling policies.

Patrice Bernassola
+1  A: 

Instead of dealing with the threading yourself you can use the asynchronous interface of QTcpSocket. Check out the Fortune Client example:

http://doc.qt.nokia.com/4.1/network-fortuneclient.html

Scott Danahy
That looks like what I need, but my sockets are not TCP (they are L2CAP bluetooth sockets). Is there anything similar? I can't find anything, but that doesn't mean there isn't :-)
cube
I've not used it, but this class from the bluetooth module looks right: http://doc.qt.nokia.com/qtextended4.4/qbluetoothl2capsocket.html
Scott Danahy
A: 

A not too elegant, but simple and working solution: Create a pipe and let select wait for either the pipe or my socket. This way I can stop the wait anytime by writing something to the pipe.

cube