C++11 线程不以 SDL 结尾



>我有两个线程 显示变色的 SDL 窗口。它编译并运行良好,但我无法通过单击窗口的关闭按钮来关闭它们。

这是我的代码:-

#include <iostream>
#include <SDL2/SDL.h>
#include <thread>
using namespace std;
void th(string name,int x,int y,int w,int h,Uint32 flags)
{
    int i=0,o=0,p=0;
    SDL_Window *win;
    SDL_Event e;
    win = SDL_CreateWindow(name.c_str(),x,y,w,h,flags);
    SDL_ShowWindow(win);
    SDL_Surface *win_sur = SDL_GetWindowSurface(win);
    SDL_FillRect(win_sur,0,SDL_MapRGB(win_sur->format,i,o,p));
    SDL_UpdateWindowSurface(win);
    while(1)
    {
        while(SDL_PollEvent(&e))
        {
            if(e.type == SDL_QUIT)
                goto end;
        }
        SDL_FillRect(win_sur,0,SDL_MapRGB(win_sur->format,i,o,p));
        SDL_UpdateWindowSurface(win);
        i++;o+=2;p+=3;
        SDL_Delay(10);
    }
    end:
    SDL_DestroyWindow(win);
}
int main()
{
    int lk =0;
    SDL_Init(SDL_INIT_VIDEO);
    thread t1(th,"win1",90,100,500,500,SDL_WINDOW_OPENGL);
    thread t2(th,"win2",10,400,500,500,SDL_WINDOW_OPENGL);
    t1.join();
    t2.join();
    SDL_Quit();
}

我正在使用 gcc 7.3 和 Linux

从文档中:

只能在设置视频模式的线程中调用此函数

在您的情况下,由于您在主线程中调用SDL_Init(SDL_INIT_VIDEO),因此您也只能在那里调用SDL_PollEvent。它可能永远不会在您的其他线程中返回任何内容。

此外,当用户单击最后一个现有窗口的关闭按钮时,会生成SDL_QUIT。当您有多个窗口时,请查看SDL_WINDOWEVENT_CLOSE(甚至默认情况下,它可能是更好的选择(。

最新更新