SDL窗口线程

时间:2015-10-08 09:40:05

标签: c++ multithreading sdl

我有一个Storage类,它基本上是我的应用程序,它持有并操纵它的数据。

在一个单独的线程中,我想要一个SDL窗口,它不断地(每隔几毫秒)将一些Storage对象的数据绘制到屏幕上。窗口应允许交互(如缩放),但修改Storage对象中的数据,它只是读取它们!

我的主要职能:

int main(int argc, char* argv[])
{    
    Storage storage;        // The object which holds the data to be displayed in the following window

    GridWindow *grid = new GridWindow (&storage);
    std::thread t(&GridWindow ::init, grid);

    std::this_thread::sleep_for(std::chrono::seconds(1));  // wait a bit to see if the window reacts to the new data

    // put some data into memory
    storage.RandomDataGeneration();

    // prevent the main function from exiting
    int a;
    std::cin >> a;
    return 0;
}

我的GridWindow.cpp:

#include "GridWindow.h"
#include <thread>

GridWindow::GridWindow(Storage* storage)
    : storage(storage)
{       
}

GridWindow::~GridWindow(){
    // Close and destroy the window
    SDL_DestroyWindow(window);
    SDL_Quit();
}

void GridWindow::init()
{
    SDL_Init(SDL_INIT_VIDEO);              // Initialize SDL2        
    window = SDL_CreateWindow(
        "An SDL2 window",                  // window title
        SDL_WINDOWPOS_UNDEFINED,           // initial x position
        SDL_WINDOWPOS_UNDEFINED,           // initial y position
        window_width,                      // width, in pixels
        window_height,                     // height, in pixels
        SDL_WINDOW_OPENGL                  // flags - see below
        );

    drawGrid();
    return;
}

void GridWindow::drawGrid()
{
    while (true){
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            // handle your event here
        }           

            SDL_Renderer* renderer = NULL;
    renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED);

    // Set Background Color
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

    // Clear window
    SDL_RenderClear(renderer);

            // draw some rectangles in the Color provided in the storage object
    for (int i = 0; i <= 100; i++){
        SDL_Rect r;
        r.x = i*10
        r.y = 1;
        r.w = 10;
        r.h = 10;

        SDL_SetRenderDrawColor(renderer, storage.rcolor, storage.gcolor, storage.bcolor, 255);

        SDL_RenderFillRect(renderer, &r);
    }

    // Render the rect to the screen
    SDL_RenderPresent(renderer);
    SDL_Delay(80);

    }
    return;
}

显示窗口并执行绘图,但它显示RandomDataGeneration()调用之前的数据。问题出在哪里?

0 个答案:

没有答案