Ubuntu18.04 SDL函数SDL_CreateRenderer多线程调用崩溃之单线程的解决方案

先创建好Render后再调用其他:

#include 
#include "include/SDL.h"
#include "include/SDL_ttf.h"

#include 
#include 
#include 

#define MAX_THREAD_NUMBER   100

TTF_Font *m_font = NULL;
SDL_Window *Screen[1024] = {NULL};//创建窗口
SDL_Renderer *render[1024] = {NULL};
int Test(void* pData)
{
    if(pData){
        int nIndex = *(int*)(pData);
        if(Screen[nIndex]){
            if(render[nIndex]){
                //...其他操作

                //
                SDL_RenderPresent(render[nIndex]);

                //
                SDL_Event event;
                while (1){
                    SDL_PollEvent(&event);
                    if (event.type == SDL_QUIT){
                        break;
                    }
                }
            }
        }

        delete pData;
        pData = NULL;
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TTF_Init();
    m_font = TTF_OpenFont("/usr/share/fonts/opentype/noto/NotoSerifCJK-Black.ttc", 100);
    if (!m_font){
        return 0;
    }

    //
    SDL_Init(SDL_INIT_EVERYTHING);//SDL只初始化一次

    for(int i = 0; i < MAX_THREAD_NUMBER; i++){
        Screen[i] = SDL_CreateWindow("Title", 100, 100, 640, 480, SDL_WINDOW_RESIZABLE);//在线程外创建窗口
        if(Screen[i]){
            render[i] = SDL_CreateRenderer(Screen[i], -1, 0);//创建渲染器
        }
    }
    for(int i = 0; i < MAX_THREAD_NUMBER; i++){
        int* pData = new int(i);
        SDL_CreateThread(Test, "", pData);
    }

    sleep(1000000);//类似等待界面退出
    for(int i = 0; i < MAX_THREAD_NUMBER; i++){
        if(Screen[i]){
            SDL_DestroyWindow(Screen[i]);//销毁窗口
            Screen[i] = NULL;
        }
        if(render[i]){
            SDL_DestroyRenderer(render[i]);//释放渲染器
            render[i] = NULL;
        }
    }

    TTF_CloseFont(m_font);//释放字体资源
    TTF_Quit();
    SDL_Quit();//退出

    return a.exec();
}

 

你可能感兴趣的:(Linux,SDL2.0)