Fix QGeoAreaMonitorPolling implementation
To avoid deadlocks in multi-threaded scenarios.
The class overrides QObject::(dis)connectNotify() methods to
check if it has any connected objects and decide if it needs
to start or stop area monitoring.
This also supports usecases when the objects connect and
disconnect from different threads (not the same thread, in
which the QGeoAreaMonitorPolling instance lives).
The tst_QGeoAreaMonitorPolling::multipleThreads() test was
sporadically hanging in the CI, indicating that there can be
some deadlock.
A more deep investigation revealed that the following flow
can happen:
1. The last PositionConsumerThread::run() method finishes and
its enterSpy gets destroyed.
2. QSignalSpyPrivate is a QObject, so upon its destruction it
invokes the QObject d-tor that calls signalSlotLock(this).
The signalSlotLock() function selects a mutex from a global
array of mutexes based on the address of the passed pointer.
The selected mutex is then locked.
3. After that the same QObject d-tor invokes disconnectNotify()
on all connected senders, including the QGeoAreaMonitorPolling
instance.
4. As it is the last connection, the
QGeoAreaMonitorPollingPrivate::checkStartStop() is called,
which ends up calling source->stopUpdates().
5. The stopUpdates() implementation emits the updatesStopped()
signal, which immediately triggers QMetaObject::activate()
and doActivate(), because there is a QSignalSpy connected to
this signal via a direct connection.
6. The doActivate() methods calls signalSlotLock(receiver), and
due to the logic described in step 2, it may try to lock the
same mutex as earlier. That is where we get the deadlock.
I was able to see it in the debugger.
This patch fixes it by making sure that source->startUpdates()
and source->stopUpdates() in checkStartStop() are always invoked
via QueuedConnection instead of being executed directly. This
makes sure that the QObject d-tor on step 3 is finished and the
mutex is unlocked before the updatesStopped() signal is emitted
at step 5.
It amends 6cc553b1579f6448e2a2734bbb4348e30b6ff09e which already
tried to solve a similar issue.
Note, however, that this is a behavior change. That's why I
prefer to keep this fix in dev only.
[ChangeLog][Important Behavior Changes][QGeoAreaMonitorPolling]
The startUpdates() and stopUpdates() methods of the underlying
position source are now always invoked via a QueuedConnection.
This means that they are always executed in the same thread
where the source lives. Previously e.g. the stopUpdates() method
could be executed from the thread where the last watcher lives.
It also means that the updates are stopped not immediately after
the last watcher is disconnected, but when the control reaches
the event loop in the source's thread.
Fixes: QTBUG-142093
Change-Id: Ic48e04bb49d9fe6e2565368a2dd327c45db5b116
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>