围绕函数调用 std::thread() 的工作方式不同

404*_*und 1 c++ opengl multithreading glfw imgui

这段代码有什么原因吗:

int main(int argc, char* argv[])
{

    Main::Init();
    std::thread worker(Main::Mainloop);
    worker.join();
    Main::Free();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

应该与此处的代码不同:

int main(int argc, char* argv[])
{

    Main::Init();
    Main::Mainloop();
    Main::Free();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意Main该类被定义为单例,这里是代码: main.h

#pragma once

#ifndef MAIN_H
#define MAIN_H


#include "window.h"


#include "mainloop.h"


 

class Main    ///Singleton
{
public:
    Main(const Main&) = delete;
    Main(Main&&) = delete;
    Main& operator=(const Main&) = delete;
    Main& operator=(Main&&) = delete;



private:
    Main();


    static Main& Get_Instance();


    friend int main(int argc, char* argv[]);


    static void Mainloop();
    static void Init();
    static void Free();


};



#endif // MAIN_H
Run Code Online (Sandbox Code Playgroud)

上面的第一个示例无法初始化其中一个GLFW, GLEW, and ImGui是我在我的程序中使用的。我试图拆分程序的初始化,但后来遇到了这个问题。当我挖得更远时,我达到了这一点,这对于为什么它不起作用没有任何意义。基本上它要么抛出异常,要么 ImGui 在运行时向我发送垃圾邮件,并说:

failed to compile vertex shader!
failed to compile fragment shader!
failed to link shader program! (with GLSL `#version 460`)
Run Code Online (Sandbox Code Playgroud)

然而窗口打开了,我只在运行时使用线程示例获得这些。不是和另一个。

Nic*_*las 5

所有这些库都以某种方式与 OpenGL 交互,因此它们正在执行的线程非常敏感。当前的 OpenGL 上下文是线程特定的;每个线程都有自己的当前上下文,并且一个上下文在任何时候都只能是一个线程中的当前上下文。

创建 GLFW 窗口会创建一个 OpenGL 上下文。如果您随后切换到另一个线程,则该上下文将不会在该线程中处于当前状态,除非您告诉 GLFW 使其在该线程中处于当前状态。

  • @prtwrt:不一定,但您必须将上下文重新分配给正在执行 OpenGL 命令的线程。请参阅 [`glfwMakeContextCurrent`](https://www.glfw.org/docs/3.3/group__context.html#ga1c04dc242268f827290fe40aa1c91157) (2认同)