[Interest] Is QLocalSocket reentrant?

Bo Thorsen bo at vikingsoft.eu
Wed May 27 22:59:58 CEST 2015


Den 22-05-2015 kl. 14:43 skrev Calogero Mauceri:
>
>
> Il 5/22/2015 2:35 PM, Calogero Mauceri ha scritto:
>> Hi all,
>>
>> sorry if this is a stupid question, but I'm having some weird memory
>> corruption problems when using QLocalSocket in multiple threads.
>>
>> I have a server process, accepting connections from client processes
>> through a QLocalServer instance. Every time a new connection is accepted
>> by the QLocalServer, the server launches a thread that communicates with
>> the client through the QLocalSocket.
>>
>> The code I'm using to launch the threads in the server is something like
>> this
>>
>> void LocalServer::newClientConnectionSlot()
>> {
>> QLocalSocket *localSocket = localServer->nextPendingConnection();
>>        if (localSocket) {
>> QThread *thread= new QThread;
>> MyWorker *worker = new MyWorker();
>> worker ->moveToThread(thread);
>>
>> thread->start();
>>
>>            localSocket->setParent(NULL);    // remove local server parent
>> in order to properly use the socket on another thread
>>            localSocket->moveToThread(thread);
>>            rpcPingReplyer->setLocalSocket(localSocket);
>> rpcPingReplyer->startPingReplying();
>>        }
>> }
>>
>> Each thread is using its own localSocket to communicate with the client.
>>
>> My question is, is it safe to use different instances of QLocalSocket
>> from different threads without guarding those sockets? The documentation
>> does not report QLocalSocket is reentrant. What does it imply? Should I
>> guard all QLocalSocket instances with a global mutex before using them?
>>
>> Thanks in advance for your hints!
>> Calogero
> Sorry, the example I previously wrote was not fully correct.
> Here is a better one
>
> void LocalServer::newClientConnectionSlot()
> {
>        QLocalSocket *localSocket = localServer->nextPendingConnection();
>        if (localSocket) {
>           QThread *thread= new QThread;
>           MyWorker *worker = new MyWorker();
>           worker->moveToThread(thread);
>
>           thread->start();
>
>           // move local socket to thread
>           localSocket->setParent(NULL);
>           localSocket->moveToThread(thread);
>           worker->setLocalSocket(localSocket);
>
>           // start communicating with client
>           worker->startCommunicate();
>        }
> }

I think the problem you have is in the last line of the code. This 
should probably be

connect(thread, SIGNAL(started()), worker, SLOT(startCommunicate()));

The difference is in which thread you are running the startCommunicate() 
function. In your code, it's running in the creating thread, but when 
connecting to started() it is in the created thread. Which changes the 
thread affinity of any QObject instances created in the function.

Bo.

-- 
Viking Software
Qt and C++ developers for hire
http://www.vikingsoft.eu



More information about the Interest mailing list