Sign in to follow this  
Humblest

OpenGL Does wglMakeCurrent() leak memory in a worker thread?

Recommended Posts

Hi, all:

I've been programming server-side offscreen rendering with OpenGL under MS Windows. The workflow consists of the following steps:
1. A client sends a request for volume rendering.
2. Server receives the request, forks a worker thread to do some ray-casting with parameters contained in the request.
3. Server retrieves the rendered image, sends it to the client and terminates the worker thread.

It works fine at first. However, after 10,000 requests, wglMakeCurrent() will fail and significant memory leak can be detected. So I make a simplified test program which contains only OpenGL context creation and deletion. It's shown below. wglMakeCurrent() always fails after about 10,000 loops. Can somebody tell me if there's anything wrong with the code? I'm using Nvidia Quadro GPU, the driver version is 307.45, OS is Windows 7 64-bit.

 

 

#include <cstdio>
#include <windows.h>
#include <tchar.h>
#include <process.h>

LRESULT CALLBACK WndProc_GL(HWND handle, UINT message, WPARAM w_param, LPARAM l_param)
{
  return DefWindowProc(handle, message, w_param, l_param);
}//-------------------------------------------------------

unsigned int __stdcall OpenglThreadProc(void *ptr_input)
{
  HINSTANCE inst_handle = GetModuleHandle(NULL);
  WNDCLASS wnd_class = {CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
    (WNDPROC)WndProc_GL,
    0, 0, inst_handle, NULL, NULL, NULL, NULL,
    _T("OpenGL Hidden Window Class")
  };
  if (!RegisterClass(&wnd_class)) return 0;
  HWND window_handle = CreateWindow(_T("OpenGL Hidden Window Class"),
    _T("Window For OpenGL"),
    WS_OVERLAPPEDWINDOW|WS_CLIPSIBLINGS|WS_CLIPCHILDRE N, 0, 0, 256, 256,
    NULL, NULL, inst_handle, NULL);
  if (!window_handle) return 0;
  HDC dc_handle = GetDC(window_handle);
  PIXELFORMATDESCRIPTOR ogl_pfd = {sizeof(PIXELFORMATDESCRIPTOR), 1,
    PFD_SUPPORT_OPENGL,
    PFD_TYPE_RGBA, 32,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    24, 8, 0,
    PFD_MAIN_PLANE,
    0, 0, 0, 0
  };
  int pixel_format = ChoosePixelFormat(dc_handle, &ogl_pfd);
  if (!SetPixelFormat(dc_handle, pixel_format, &ogl_pfd)) return 0;
    HGLRC rc_handle = wglCreateContext(dc_handle);
  if (!rc_handle || !wglMakeCurrent(dc_handle, rc_handle)) return 0;

  _tprintf_s(_T("Executing Thread %d.\n"), *(reinterpret_cast<int*>(ptr_input)) + 1);

  // Deletes OpenGL context and destroys window.
  wglMakeCurrent(NULL, NULL);
  wglDeleteContext(rc_handle);
  ReleaseDC(window_handle, dc_handle);
  DestroyWindow(window_handle);
  UnregisterClass(_T("OpenGL Hidden Window Class"), GetModuleHandle(NULL));
  return 1;
}//--------

int main (const int argc, TCHAR *argv[])
{
  int i = 0;
  for (; i < 20000; i++) {
    HANDLE running_thread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
      OpenglThreadProc, &i, 0, NULL));
    WaitForSingleObject(running_thread, INFINITE);
    CloseHandle(running_thread);
  }
  return 1;
}//---------

 

 

I found something confusing with this test program. wglMakeCurrent() creates a Windows user object every time it's called, but this object is not released in wglDeleteContext(). It still exists even after the worker is terminated, causing a memory leak. There is a per-process limit of user objects under Windows, so the program will eventually fail.

When the code of context creation/deletion is moved to the main thread, wglMakeCurrent() doesn't create new user object after the first invocation. So it seems that wglMakeCurrent() only create new user object in new threads. But since the OpenGL context is explicitly deleted and the thread is terminated, resources associated with that context should be released as well. I'm not sure it's the fault with my code or the driver. Can somebody help me with this?

Share this post


Link to post
Share on other sites
I can't tell whether [tt]wglMakeCurrent[/tt] really leaks or whether there is a different reason for what you see, but if you need to call [tt]wglMakeCurrent[/tt] more than 2-3 times in a program, you're very likely doing something wrong.

Usually you will have one render thread (for most people that is the main thread, too). Often you have worker threads to fill buffers (given a pointer to a mapping), too.
Sometimes you have shared contexts and two threads (one for rendering, one for uploading data), but this is rarely done both for added overhead and complexity.

You really never want to have a hundred or a thousand threads with a hundred/thousand contexts. You also really do not want to call [tt]wglMakeCurrent[/tt] in the middle of your program, because it kills the pipeline.

What you want to do is create one (or at most two or three) threads that will deal with OpenGL, and one (or at most two or three) contexts. Then you want to make exactly one context current in one thread. And then you never want to change that again. Edited by samoth

Share this post


Link to post
Share on other sites
I can't tell whether [tt]wglMakeCurrent[/tt] really leaks or whether there is a different reason for what you see, but if you need to call [tt]wglMakeCurrent[/tt] more than 2-3 times in a program, you're very likely doing something wrong.

Usually you will have one render thread (for most people that is the main thread, too). Often you have worker threads to fill buffers (given a pointer to a mapping), too.
Sometimes you have shared contexts and two threads (one for rendering, one for uploading data), but this is rarely done both for added overhead and complexity.

You really never want to have a hundred or a thousand threads with a hundred/thousand contexts. You also really do not want to call [tt]wglMakeCurrent[/tt] in the middle of your program, because it kills the pipeline.

What you want to do is create one (or at most two or three) threads that will deal with OpenGL, and one (or at most two or three) contexts. Then you want to make exactly one context current in one thread. And then you never want to change that again.

For each thread, there's one dedicated OpenGL context and only one wglMakeCurrent(). This is a server rendering program rather than a desktop application, each thread is responding to one client request and doing its own job. No OpenGL context is shared among them. The maximum number of concurrency won't be high, but concurrency is required.

Share this post


Link to post
Share on other sites

What you describe should actually be a legitimate way of using OpenGL, and should cause no problems (both in regards of errors and performance). Did you try if you actually need wglMakeCurrent at all? If you create a context in the worker thread, it should already be current in that one. Since you don't really want it to be current anywhere else, why not just leave it that way?

 

This still doesn't answer the question whether wglMakeCurrent leaks, but it might just solve your problem (or, it might shift your problem to wglCreateContext eventually failing -- I hope not).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Partner Spotlight

  • Forum Statistics

    • Total Topics
      627643
    • Total Posts
      2978362
  • Similar Content

    • By xhcao
      Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness. 
    • By cebugdev
      hi guys, 
      are there any books, link online or any other resources that discusses on how to build special effects such as magic, lightning, etc. in OpenGL? i mean, yeah most of them are using particles but im looking for resources specifically on how to manipulate the particles to look like an effect that can be use for games,. i did fire particle before, and I want to learn how to do the other 'magic' as well.
      Like are there one book or link(cant find in google) that atleast featured how to make different particle effects in OpenGL (or DirectX)? If there is no one stop shop for it, maybe ill just look for some tips on how to make a particle engine that is flexible enough to enable me to design different effects/magic 
      let me know if you guys have recommendations.
      Thank you in advance!
    • By dud3
      How do we rotate the camera around x axis 360 degrees, without having the strange effect as in my video below? 
      Mine behaves exactly the same way spherical coordinates would, I'm using euler angles.
      Tried googling, but couldn't find a proper answer, guessing I don't know what exactly to google for, googled 'rotate 360 around x axis', got no proper answers.
       
      References:
      Code: https://pastebin.com/Hcshj3FQ
      The video shows the difference between blender and my rotation:
       
    • By Defend
      I've had a Google around for this but haven't yet found some solid advice. There is a lot of "it depends", but I'm not sure on what.
      My question is what's a good rule of thumb to follow when it comes to creating/using VBOs & VAOs? As in, when should I use multiple or when should I not? My understanding so far is that if I need a new VBO, then I need a new VAO. So when it comes to rendering multiple objects I can either:
      * make lots of VAO/VBO pairs and flip through them to render different objects, or
      * make one big VBO and jump around its memory to render different objects. 
      I also understand that if I need to render objects with different vertex attributes, then a new VAO is necessary in this case.
      If that "it depends" really is quite variable, what's best for a beginner with OpenGL, assuming that better approaches can be learnt later with better understanding?
       
    • By test opty
      Hello all,
       
      On my Windows 7 x64 machine I wrote the code below on VS 2017 and ran it.
      #include <glad/glad.h>  #include <GLFW/glfw3.h> #include <std_lib_facilities_4.h> using namespace std; void framebuffer_size_callback(GLFWwindow* window , int width, int height) {     glViewport(0, 0, width, height); } //****************************** void processInput(GLFWwindow* window) {     if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)         glfwSetWindowShouldClose(window, true); } //********************************* int main() {     glfwInit();     glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);     glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);     glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);     //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);     GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);     if (window == nullptr)     {         cout << "Failed to create GLFW window" << endl;         glfwTerminate();         return -1;     }     glfwMakeContextCurrent(window);     if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))     {         cout << "Failed to initialize GLAD" << endl;         return -1;     }     glViewport(0, 0, 600, 480);     glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);     glClearColor(0.2f, 0.3f, 0.3f, 1.0f);     glClear(GL_COLOR_BUFFER_BIT);     while (!glfwWindowShouldClose(window))     {         processInput(window);         glfwSwapBuffers(window);         glfwPollEvents();     }     glfwTerminate();     return 0; }  
      The result should be a fixed dark green-blueish color as the end of here. But the color of my window turns from black to green-blueish repeatedly in high speed! I thought it might be a problem with my Graphics card driver but I've updated it and it's: NVIDIA GeForce GTX 750 Ti.
      What is the problem and how to solve it please?
  • Popular Now