Can you draw UI stuff from a background Thread?

I was trying an experiment to see if I could use a background thread to draw some UI things, and although it seems to work, I am seeing these strange purple warnings in Xcode like this:

-[NSView frame] must be used from main thread only
-[NSView window] must be used from main thread only

This is apparently a result of using calls like getBounds() in the code that is being drawn by the thread.

I did copy the basic approach from the multithreading demo, i.e. using a MessageManagerLock:

    void run() override
        // this is the code that runs this thread - we'll loop continuously,
        // updating the coordinates of our blob.

        // threadShouldExit() returns true when the stopThread() method has been
        // called, so we should check it often, and exit as soon as it gets flagged.
        while (! threadShouldExit())
            // sleep a bit so the threads don't all grind the CPU to a halt..
            wait (interval);

            // because this is a background thread, we mustn't do any UI work without
            // first grabbing a MessageManagerLock..
            const MessageManagerLock mml (Thread::getCurrentThread());

            if (! mml.lockWasGained())  // if something is trying to kill this job, the lock
                return;                 // will fail, in which case we'd better return..

            // now we've got the UI thread locked, we can mess about with the components

Is this not something that can or should be done?

You can’t do the actual rendering from the BG thread, but you can render into an image on a BG thread, and then pass this image back to the main thread for rendering.

1 Like