2015-06-13 36 views
0

如果我有一個做以下的功能:的Win32消息泵和std ::線程用於創建OpenGL上下文和渲染

bool foo::init() 
{ 
    [Code that creates window] 
    std::thread run(std::bind(&foo::run, this)); 

    while (GetMessage(&msg, NULL, 0, 0)) { 
     TranslateMessage(&msg); 
     DispatchMessage(&msg); 
    } 
} 

其中行程被定義爲:

void foo::run() 
{ 
    [Code that creates initial opengl context] 
    [Code that recreates window based on new PixelFormat using wglChoosePixelFormatARB] 
    [Code that creates new opengl context using wglCreateContextAttribsARB] 

    do { 
     [Code that handles rendering] 
    } while (!terminate); 
} 

由於窗口在渲染線程上重新創建,並且消息泵將在主線程上執行,這被認爲是安全的? WndProc會被調用什麼函數?上面的代碼可能被認爲是不好的設計,但這不是我所感興趣的。我只對定義的行爲感興趣。

回答

2

Win32窗口綁定到創建它的線程。 只有那個線程可以接收和發送窗口的消息,而只有那個線程可以銷燬這個窗口。

因此,如果您在工作線程內重新創建窗口,那麼該線程必須接管管理窗口並分派其消息的責任。

否則,您需要將窗口的重新創建委託給主線程,以便它保留在最初創建它的同一個線程中。

bool foo::init() 
{ 
    [Code that creates window] 

    std::thread run(std::bind(&foo::run, this)); 

    while (GetMessage(&msg, NULL, 0, 0)) { 
     if (recreate needed) { 
      [Code that recreates window and signals worker thread] 
      continue; 
     } 
     TranslateMessage(&msg); 
     DispatchMessage(&msg); 
    } 
} 

void foo::run() 
{ 
    [Code that creates initial opengl context] 

    [Code that asks main thread to recreate window based on new PixelFormat using wglChoosePixelFormatARB, and waits for signal that the recreate is finished] 

    [Code that creates new opengl context using wglCreateContextAttribsARB] 

    do { 
     [Code that handles rendering] 
    } while (!terminate); 
} 

否則,調用在主線程wglChoosePixelFormatARB()開始工作線程之前,並存儲所選擇的PixelFormat其中線程可以訪問它。

bool foo::init() 
{ 
    [Code that creates window] 
    [Code that gets PixelFormat using wglChoosePixelFormatARB] 

    std::thread run(std::bind(&foo::run, this)); 

    while (GetMessage(&msg, NULL, 0, 0)) { 
     TranslateMessage(&msg); 
     DispatchMessage(&msg); 
    } 
} 

void foo::run() 
{ 
    [Code that creates opengl context using wglCreateContextAttribsARB] 

    do { 
     [Code that handles rendering] 
    } while (!terminate); 
} 
+0

我明白了,儘管我認爲在調用wglChoosePixelFormatARB之前必須首先創建窗口。 wgl函數依賴於HDC的存在,如果我有HWND,我只能得到HDC。研究基於這個輸入重構我的代碼。 –