[Kde-pim] KABC::ResourceCached thread-safety concern

Kevin Krammer kevin.krammer at gmx.at
Tue Aug 10 13:46:34 BST 2010


On Tuesday, 2010-08-10, Dmitry Savenko wrote:
> Hello!
> I'm developing a CardDAV connector based on KABC::ResourceCached. It's
> unclear for me how to use the class with threads safely.
> Consider the following case:
> 
> 1. asyncLoad() is called.
> 2. A new thread is created, a slot is connected to its finished()
> signal. loadingFinished() (or loadingError()) will be emitted from
> this slot.
> 3. asyncLoad() returns, the thread is working.
> 4. The thread downloaded vcards from the server and parsed them. Now
> it needs to insert addressees to the resource (insertAddressee()
> method);
> 5.1. Kontact decides to read the resource during the process of
> inserting new addressees. Crash.
>  or
> 5.2. A user adds a new contact during the process of inserting new
> addressees. Crash.
> 
> Is this scenario possible? I mean I don't see how to protect
> insertAddressee() call in multi-threaded environment. May be, I've
> missed something?

You could lock a mutex in your class' insertAddressee() before calling the 
base class implementation and do the same when calling the base class' 
implementation from the thread.

Or you let the thread emit a signal with the addressees and use a 
Qt::QueuedConnection to connect to a slot in your resource class so it gets 
called by the main loop thread instead.

Or put the data into a mutex protected member and use 
QMetaObject::invokeMethod() with Qt::QueuedConnection to call a slot with the 
main loop thread which then processes the member, again locked by mutex.

Or instead of using a QThread directly use a Qt::Concurrent::run() and a 
QFutureWatcher to know when the result is available.

Basically the usual choices when the event loop thread and a worker thread 
access the same data.

Cheer,
Kevin

-- 
Kevin Krammer, KDE developer, xdg-utils developer
KDE user support, developer mentoring
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.kde.org/pipermail/kde-pim/attachments/20100810/fdc97959/attachment.sig>
-------------- next part --------------
_______________________________________________
KDE PIM mailing list kde-pim at kde.org
https://mail.kde.org/mailman/listinfo/kde-pim
KDE PIM home page at http://pim.kde.org/


More information about the kde-pim mailing list