线程化此方法会产生段错误,为什么?

threading this method produces a segfault, why?

所以我正在使用 GLFW,并且在我的主方法中调用以下方法时有效

void Display::run() {
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */



        /* Swap Buffers And Poll */
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
}

但是当我尝试在单独的线程上运行它时,我得到了一个段错误

std::thread t1(&Display::run, this);

有什么想法吗?询问您是否需要更多代码

编辑: main.cpp

#include "src/support/Display.h"

int main() {
    Display* d;
    d->start();
    return 0;
}

Display.h

#include <GLFW/glfw3.h>
#include <exception>
#include <thread>


class Display {

private:
    GLFWwindow* window;
    std::thread* displayThread;

    void run();

public:
    Display();
    void start();
    void close();
};

/* Exceptions */
struct GLFWNotInitilizedException : public std::exception
{
    const char * what () const throw ()
    {
        return "ERR: Could Not Initialize GLFW";
    }
};

struct WindowNotCreatedException : public std::exception
{
    const char * what () const throw ()
    {
        return "ERR: Could Not Create Window";
    }
};

Display.cpp

#include "Display.h"

Display::Display() {
    //init glfw
    if (!glfwInit())
        throw GLFWNotInitilizedException();

    //create window and its context
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        throw WindowNotCreatedException();
    }

    //make windows context current
    glfwMakeContextCurrent(window);

    //run(); //this works instead of calling start() which puts run() into a thread

}

/* begins the rendering of the display window contents in seperate thread */
void Display::start() {
    std::thread t1(&Display::run, this);
    displayThread = &t1;
}

/* renders contents of display window */
void Display::run() {
    while (!glfwWindowShouldClose(window)) //seg fault is output here
    {
        /* Render here */



        /* Swap Buffers And Poll */
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
}


/* to be used when closing display window */
void Display::close() {
    glfwSetWindowShouldClose(window, true);
    displayThread->join();
    glfwDestroyWindow(window);
}
Display* d;

你这里没有创建对象,只是一个未初始化的指针。

d->start();

这会调用一个不存在的对象的成员。当它试图访问 run() 函数中的任何成员时,它只是访问垃圾,因为没有对象。

您可能想像这样创建一个对象:

Display d;
d.start();

你的启动函数也会终止程序,因为你没有在线程被销毁之前加入它。在尝试像这样使用线程和指针之前,您应该学习 C++ 对象生命周期的基础知识。

在了解基础知识之前,请停止使用指针。 displayThread 应该是一个实际的 std::thread 而不是指向某些超出范围的 std::thread 的指针。

那么你可以这样做:

void Display::start() {
    displayThread = std::thread(&Display::run, this);
}

确保在销毁之前调用 displayThread.join(),例如在 Display 析构函数中。

//make windows context current
glfwMakeContextCurrent(window);

这使其在 CURRENT 线程上处于活动状态。 运行 这在您要渲染的线程上,它应该可以工作。目前它在构造函数中。