When I use tbb::parallel_invoke to separate the input loop from the render loop into two different threads, both loops are running, but the window from glfw freezes immediately.
The following is the trimmed down version of the code that still yields the error, note that the relevant part is the main function:
#include <glad/glad.h>
// glad needs to be included before GLFW
#include <GLFW/glfw3.h>
#include <tbb/tbb.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
class Window
{
public:
unsigned int const SCREEN_WIDTH = 800;
unsigned int const SCREEN_HEIGHT = 600;
GLFWwindow* w;
Window()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
glfwWindowHint(GLFW_RESIZABLE, false);
w = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Simulation", nullptr, nullptr);
glfwMakeContextCurrent(w);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
throw -1;
}
glfwSetFramebufferSizeCallback(w, framebuffer_size_callback);
// OpenGL configuration
// --------------------
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
};
int main()
{
Window window;
tbb::parallel_invoke(
[&]() -> void // Simulation
{
while (!glfwWindowShouldClose(window.w))
{
std::cout << "Render loop" << std::endl;
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window.w);
glfwPollEvents();
}
},
[]() -> void // Input and Time
{
while (true)
{
std::cout << "Input loop" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
glfwTerminate();
return 0;
}
As you can see these loops are completely separated from each other.
Deleting the while loop from the input (e.g. just outputting “input loop” once) fixes the issue and the program runs perfectly even within the invoke.
Interesting is also that the output in the render loop also continues, while the window freezes. Meaning both threads must still be running.
I have also tried using tbb::task_group/tbb::task_arena but the same issues arise.
Using OpenMP works fine, but I wanted to try using tbb.
Any help is much appreciated, thanks!
Steegi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.