diff options
author | Tor Arne Vestbø <[email protected]> | 2025-05-28 20:45:12 +0200 |
---|---|---|
committer | Tor Arne Vestbø <[email protected]> | 2025-05-31 01:16:23 +0200 |
commit | e9dbdaa499c6d5b41d467400886d15824043ad57 (patch) | |
tree | b0c1dae68783e11b2ad6ce12e664b64e5c31f26a | |
parent | 11f149d987bf35332a5d78bf51f9ac1f1a375663 (diff) |
Make QOpenGLContext::globalShareContext() lazy creation thread-safe
We move the context to the main thread (or the thread of qGuiApp),
as that's where it will be deleted.
Amends 4a7ccb65f0065e878c5762db05eca9c5cd6731e5.
Caught-by: Eskil Abrahamsen Blomfeldt <[email protected]>
Change-Id: I8e5dc512dce02d22980730a46474b2262684a713
Reviewed-by: Allan Sandfeld Jensen <[email protected]>
-rw-r--r-- | src/gui/kernel/qopenglcontext.cpp | 5 | ||||
-rw-r--r-- | tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp | 18 |
2 files changed, 23 insertions, 0 deletions
diff --git a/src/gui/kernel/qopenglcontext.cpp b/src/gui/kernel/qopenglcontext.cpp index fa6572300b2..d49886087c0 100644 --- a/src/gui/kernel/qopenglcontext.cpp +++ b/src/gui/kernel/qopenglcontext.cpp @@ -968,11 +968,16 @@ bool QOpenGLContext::supportsThreadedOpenGL() QOpenGLContext *QOpenGLContext::globalShareContext() { Q_ASSERT(qGuiApp); + + static QMutex mutex; + QMutexLocker locker(&mutex); + // Lazily create a global share context when enabled unless there is already one if (!qt_gl_global_share_context() && qGuiApp->testAttribute(Qt::AA_ShareOpenGLContexts)) { QOpenGLContext *ctx = new QOpenGLContext; ctx->setFormat(QSurfaceFormat::defaultFormat()); ctx->create(); + ctx->moveToThread(qGuiApp->thread()); qt_gl_set_global_share_context(ctx); QGuiApplicationPrivate::instance()->ownGlobalShareContext = true; } diff --git a/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp b/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp index c6bf6c650c3..b903dc3fc1d 100644 --- a/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp +++ b/tests/auto/gui/kernel/qguiapplication/tst_qguiapplication.cpp @@ -1292,6 +1292,24 @@ void tst_QGuiApplication::globalShareContext() QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true); ctx = QOpenGLContext::globalShareContext(); QVERIFY(ctx); + + // Test that the global share context is lazily created, + // even from secondary threads. + app.reset(); + app.reset(new QGuiApplication(argc, argv)); + QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true); + class Thread : public QThread + { + void run() override + { + auto *ctx = QOpenGLContext::globalShareContext(); + QVERIFY(ctx); + QCOMPARE(ctx->thread(), qGuiApp->thread()); + } + }; + Thread thread; + thread.start(); + thread.wait(); #else QSKIP("No OpenGL support"); #endif |