Font and MessageManager::Lock clarification

Hi !

I just update juce_graphics module to Juce 5 developer branch.
And I find the “new” clever assert in Font::getStringWidthFloat and Font::getGlyphPositions:

// This call isn't thread-safe when there's a message thread running
jassert (MessageManager::getInstanceWithoutCreating() == nullptr
           || MessageManager::getInstanceWithoutCreating()->currentThreadHasLockedMessageManager());

I’m wondering why this is not thread safe ?
Is it because of ReferenceCountedObjectPtr<SharedFontInternal> Font::font;
or because of TypefaceCache::getInstance() ?

If it is related to TypefaceCache, may be we should move this assert in Font::getTypeface()
method instead because there is other extra callers that should be protected:
Font::getAscent() Font::getAvailableStyles() Font::getHeightToPointsFactor()

I’m looking at this code because I made some offscreen Juce::Image Font rendering in my OpenGL thread, so I protect my caller code with:

juce::MessageManager::Lock managerLock;
... // text rendering

Hoping that client of my code already start the dispatch loop. (I do not know the way to check it, help is welcome here)

Thanks in advance for your advices.

NB: I already have related issue 3 years before with Juce 4 here:

All the bests

Nobody can enlighten me on this?

Best regards

It was added here to guard against race conditions that can occur when calling the underlying native functions from different threads. Calling TypefaceCache::getInstance() or using ReferenceCountedObjectPtr<SharedFontInternal> isn’t the issue here as I think the JUCE graphics code is mostly thread-safe, but obviously there’s nothing we can do if the native methods that are eventually called aren’t.

It might be worth reading through these related threads to see if they can help:

Hi Ed and thanks for reply.

I review the forum posts and TypefaceCache code and everything is protected by a ReadWriteLock, so indeed, I do not think theire is any thread safety issue here.

ReferenceCountedObjectPtr<SharedFontInternal> Font::font; use atomic ReferenceCountedObject so no thread safety neither.

Everything seems perfectly elegant and fonctionning very well.
So indeed, those assert are usefull only in the case of non thread safe native methods.

Many thanks for this highlight.

All the best

In the case the font is a custom typeface, it will not call into the native stuff, so the Assert is not needed in this case.