[Qt-interest] Is QAbstractItemModel thread safe?

Sean Harmer sean.harmer at maps-technology.com
Tue Jun 30 22:55:58 CEST 2009


Ben Swerts wrote:
>> On Monday 29 June 2009 22:03:25 Eric Clark wrote:
>>     
>>> I was just wondering if it is safe to call functions in the
>>> QAbstractItemModel class from a thread that is different than the main
>>>       
>> GUI
>>     
>>> thread?
>>>       
>> The real question is whether you can call functions from
>> QAbstractItemModel
>> from any thread != QAbstractItemModel::thread() :-)
>>
>> And at least from expierience I can say that it is. I have several models
>> in
>> their own thread and access each of them with two views (naturally in the
>> gui-
>> thread) and this runs well for hours (in the range of 4-7 days:).
>>
>> The docs say that it is at least re-entreant. And I think the
>> communication
>> with the views is mostly done with signals/slots and these are sent as
>> events
>> when crossing threads. BTW: You have to do Q_DECLARE_METATYPE( QModelIndex
>> )...
>>     
>
> And I was just going to reply that it can be safe as long as you don't put a
> view on it...
>
> QAbstractItemModel notifies a QAbstractItemView by signals, so that's
> thread-safe. The view, however, then queries the model by calling its
> flags(), parent(), rowCount(), columnCount(), data(), etc. functions
> directly. I don't see how that can be thread-safe. 
>   
Well, you could potentially make it thread-safe by introducing a mutex 
into the model class and locking it appropriately. Although I would not 
like to promise it would be very performant given how often the view 
calls functions on the model. I have not tried this so I do not know if 
it is possible or even necessary in practise.

Sean




More information about the Qt-interest-old mailing list