Eadword
Eadword

Reputation: 160

SDL2 Threading Seg Fault

I am working on a rendering library for SDL2 and I am running into a seg fault when I try to do anything with the renderer. Through debugging I have determined that it is created correctly from the window (now...) However I cannot figure out why SDL2 is seg faulting when I call SDL_RenderClear(data->renderer)

The main thread calls:

int RenderThread::start(std::string title, int x, int y, int w, int h, Uint32 flags) {
    data.window = SDL_CreateWindow(title.c_str(), x, y, w, h, flags);
    if(data.window == NULL) return -2;
    data.renderer = SDL_CreateRenderer(data.window, -1, 0);
    if(data.renderer == NULL) return -3;
    data.rlist->setRenderer(data.renderer);

    data.run = true;

    if(thread == NULL)
        thread = SDL_CreateThread(renderThread, "RenderThread", (void*)(&data));
    else return 1;

    return 0;
}

Then the actual thread is:

int RenderThread::renderThread(void* d) {
    RenderData* data = (RenderData*)d;
    data->rlist->render(true);
    SDL_SetRenderDrawColor(data->renderer, 0xFF, 0xFF, 0xFF, 0xFF);
    SDL_RenderClear(data->renderer);
    while(data->run) {
        data->rlist->render();
        SDL_RenderPresent(data->renderer);
        SDL_Delay(data->interval);
    }
    return 0;
}

If you need to see more of the code it is all on github.

Upvotes: 0

Views: 549

Answers (1)

DanielKO
DanielKO

Reputation: 4517

Some platforms (e.g. Windows) don't allow interacting with windows from threads other than the one that created them.

The documentation explicitly says this:

NOTE: You should not expect to be able to create a window, render, or receive events on any thread other than the main one.


From a design's perspective, trying to render from another thread becomes the source of many problems. For instance:

  • Is it desirable to (unpredictably) update an object more than once per frame? What's preventing a logic thread from trying to make many updates that can't be rendered?
  • Is it desirable to risk re-rendering without having the chance to update an object?
  • Will you lock the entire scene while the update happens? Or will each object get its own lock, so you don't try to render an object that's in the middle of an update? Is it desirable for the frame rate to be unpredictable, due to other threads locking the objects?

Not to mention the costs of synchronization primitives.

Upvotes: 1

Related Questions