1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <SFML/Graphics.hpp>
#include <thread>
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
bool done = false;
using namespace std;
const int H = 720;
const int W = 1280;
sf::Uint8* pixels = new sf::Uint8[W * 800 * 4];
void render(int row_0, int row_1)
{
while(!done)
{
{
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
ready = false;
}
for (int ir = row_0; ir < row_1; ir++)
{
for (int ic = 0; ic < W; ic++)
{
pixels[(ir * W + ic) * 4] = 100; //red
pixels[(ir * W + ic) * 4 + 1] = 100; //green
pixels[(ir * W + ic) * 4 + 2] = 100; //blue
}
}
}
}
int main()
{
sf::RenderWindow window(sf::VideoMode(W, H), "SFML works!");
window.setFramerateLimit(0);
sf::Texture texture; texture.create(W, H);
sf::Sprite sprite(texture);
for (int ir = 0; ir < W * H * 4; ir++)
{
pixels[ir] = 255; //set alpha to max
}
thread T1(render, 0, 180);
thread T2(render, 180, 360);
thread T3(render, 360, 540);
thread T4(render, 540, 720);
while (window.isOpen())
{
//thread T1(render, 0, 180);
//thread T2(render, 180, 360);
//thread T3(render, 360, 540);
//thread T4(render, 540, 720);
//T1.join();
//T2.join();
//T3.join();
//T4.join();
render(0, 720);
texture.update(pixels);
{
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
window.draw(sprite);
window.display();
}
{
std::unique_lock<std::mutex> lck(mtx);
done = true;
ready = true;
cv.notify_all();
}
T1.join();
T2.join();
T3.join();
T4.join();
return 0;
}
| |