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