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

标签 c++ multithreading glfw

所以我使用 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;
}

显示.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";
    }
};

显示.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);
}

最佳答案

//make windows context current
glfwMakeContextCurrent(window);

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

关于c++ - 线程化此方法会产生段错误,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933812/

相关文章:

c++ - 三任务并​​行计算

c++ - 使用链接 linux 编译 GLFW 应用程序问题

c++ - 如何对视频文件使用语音识别?

c++ - 双链表中的智能指针

c++ - 在 qt main.cpp 中转换 rootobject() 以与 qml 通信时出错

android - 等待 AsyncTask 获取数据并在那之后在 UI 线程中做一些事情

java - Phaser 实例和 Spring MVC

java - 多线程与单线程

python - 如何在Python中为GLFW设置窗口提示

c++ - 如何在glfw中显示glutDisplayFunc,glutMainLoop?