#include <complex>
#include <thread>
#include "SDL.h"
#define maxt 30
long double map(long double x, long double in, long double im, long double on, long double om) { return (x - in) * (om - on) / (im - in) + on; }
void f(SDL_Window *wn, SDL_Renderer *rn, int x, int y, int maxi, long double minx, long double maxx) {
int i = 0;
std::complex<long double> z(0, 0);
std::complex<long double> c(map(x, 0, SDL_GetWindowSurface(wn)->w, minx, maxx), map(y, 0, SDL_GetWindowSurface(wn)->h, minx, maxx));
for (i; i < maxi; i++) {
z = z*z + c;
if (abs(z) > 2) { break; }
}
int col = i == maxi ? 0 : (int)map(i, 0, maxi, 0, 255);
SDL_SetRenderDrawColor(rn, col, col, col, 255);
SDL_RenderDrawPoint(rn, x, y);
}
void fmand(SDL_Window *wn, SDL_Renderer *rn, int maxi, int xn, int xm, long double minx, long double maxx) {
for (int x = xn; x < xm; x++) {
for (int y = 0; y < SDL_GetWindowSurface(wn)->h; y++) {
f(wn, rn, x, y, maxi, minx, maxx);
}
}
}
int main(int argc, char *argv[]) {
long double minx = -2, maxx = 2, zf = 0.1;
int maxi = 256;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window *wn = SDL_CreateWindow("Mandelbrot", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 800, 0);
SDL_Renderer *rn = SDL_CreateRenderer(wn, -1, 0);
SDL_RenderSetLogicalSize(rn, 800, 800);
SDL_SetRenderDrawColor(rn, 0, 0, 0, 255);
SDL_RenderClear(rn);
while (1) {
SDL_RenderPresent(rn);
//fmand(wn, rn, maxi, 0, SDL_GetWindowSurface(wn)->w, minx, maxx); this line draws the whole mandelbrot set
std::thread t[maxt];
for (int i = 0; i < maxt - 1; i++)
t[i] = std::thread(fmand, wn, rn, maxi, (int)(SDL_GetWindowSurface(wn)->w / maxt * i), (int)(SDL_GetWindowSurface(wn)->w / maxt * (i+1)), minx, maxx);
for (int i = 0; i < maxt - 1; i++)
t[i].join();
}
return 0;
}
The code above uses SDL2 to draw a mandelbrot set. The problem occurs when I apply multithreading to it. I noticed that it works when I do only one thread at a time, but not when they are working simultaneously.
I know my code doesn't look very organized, so I'll answer every question you might want to ask.
Finally, here's the error Visual Studio throws at me:
"Exception thrown at 0x00007FFC48324589 (msvcrt.dll) in SDLTest.exe: 0xC0000005: Access violation reading location 0x00007FF4AAFA7000."
User contributions licensed under CC BY-SA 3.0