Multithread - Finish one 'for' interation before continuing?

Hi everyone, i'm making my own raycasting engine and it's well functioning, sprite, ai and everything else.
In order to raise the framerate i've discovered the multithreading but i'm sure i don't get it right.


I'm raycasting from left to right, save for every vertical scan line the colors, wall distance, and averything else. What i want to do is to split this big function into two separate threads/function:

Previously the algorithm goes to scanLine=0 to scanLine=width.
Now i want a thread for scanLine=0 to scanline=width/2; and a second thread for scanLine=width/2 to scanLine=width.

I've almost make it as you can see but the two threads share some variables so it's glitchy
https://i.imgur.com/M97Isdf.png


Here's a sample code:
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
void function_one ()
{
   for (int scanLine_one = 0 ; scanLine_one < width/2 ; scanLine_one++)
   {
       funcion_a();
       funcion_b();
       funcion_c();
   }  
}

void function_two ()
{
   for (int scanLine_two = width/2 ; scanLine_two < width ; scanLine_two++)
   {
       funcion_a();
       funcion_b();
       funcion_c();
   }  
}


int main()
{
   "previous things"

   thread thread_one{function_one};
   thread thread_two{function_two};
   thread_one.join();
   thread_two.join();

   "render"
}


What i want is tho end a single 'for' iteration before passing to the next one, for one or other thread. Is that possible? Is that usefull? Or have to separate every single common variable?
What i want is tho end a single 'for' iteration before passing to the next one, for one or other thread.
So you want, for example, thread A to process once scanline, then thread B, then A, and so on? Yes, that's possible, but then your program will run no faster than if it was running single threaded.

Or have to separate every single common variable?
Yes, parallel code must use as little shared state as possible, because any shared state involves either incorrect behavior (as you saw) or synchronization, which lowers the performance.
Fortunately, raycasting is super easy to parallelize, so it shouldn't be too difficult to make the threads independent.
I had imagined it.. thank you for the answer! :)

Unfortunately i've got so much going on in rendering that it seems really hard to modify all :( damn it!
By the way, you could probably make your single-threaded code faster by rendering by column instead of by scanline. Since in raycasting all walls are vertical, all rays along a column will fall onto the same wall (although possibly floors from different rooms).
Yes, i intend a vertical scan line, it can go up to 60fps in 480x300 on a i3 2th mobile 2.4Ghz, it's not that bad right..? :/.
Maybe one day i will make the change from single to multithread, for now this costs me about 15% of fps.
Last edited on
Topic archived. No new replies allowed.