Multithreading – how to execute QObject:: movetothread() when qthreadpool is used?

I'm building a small multithreaded web server Qtcpsockets are obtained in the main thread, and then passed to qtthreadpool by qtcurrent. Qtthreadpool finally processes the data and issues the answer

My problem is that sockets are created in the main thread and processed in another thread This causes an error when attempting to write to the socket:

socket->write(somedata);

The clean way is to use to move the socket object to the processing thread

socket->moveToThread(QThread::currentThread()).

However, this can only be invoked in the thread that creates the object. In addition, the socket takes the qtcpserver object as the parent object, so movetothread() will fail anyway (the parent object cannot switch threads)

How do I move an object to qthread:: currentthread() in the code running in the thread pool? Or, how do I write a socket outside the thread that created it?

Solution

Extend qtcpserver, re implement incomingconnection (int socket descriptor) and pass socket descriptor to threads in the pool Let qrunnable create qtcpsocket from descriptor and start event loop to receive signal from the socket

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>