【发布时间】:2018-03-15 18:40:18
【问题描述】:
我有两个线程显示变色 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
【问题讨论】:
-
存在数据竞争:两个线程将尝试在不同步的情况下读取和写入
e全局变量。与其他变量相同。而且你永远不会打电话给SDL_DestroyWindow来摆脱窗户。 -
@VTT 我已经编辑了代码,但仍然无法工作。
-
你也应该处理
SDL_WINDOWEVENT_CLOSE事件。
标签: c++ multithreading sdl-2