Umbranocturna
Umbranocturna
CC#
Created by Umbranocturna on 9/17/2023 in #help
How to efficiently use Threads and locks
I'm writing a short program that computes the mandelbrot set. I have implemented threads, but ts my first time using them and i'm a little confused.
Thread thread1 = new Thread(() => bitmapRenderer.UpdateBitmap(0,height/8));
Thread thread2 = new Thread(() => bitmapRenderer.UpdateBitmap(height/8,2*height/8));
Thread thread3 = new Thread(() => bitmapRenderer.UpdateBitmap(2*height/8,3*height/8));
Thread thread4 = new Thread(() => bitmapRenderer.UpdateBitmap(3*height/8,4*height/8));
Thread thread5 = new Thread(() => bitmapRenderer.UpdateBitmap(4*height/8,5*height/8));
Thread thread6 = new Thread(() => bitmapRenderer.UpdateBitmap(5*height/8,6*height/8));
Thread thread7 = new Thread(() => bitmapRenderer.UpdateBitmap(6*height/8,7*height/8));
Thread thread8 = new Thread(() => bitmapRenderer.UpdateBitmap(7*height/8,height));

thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
thread5.Start();
thread6.Start();
thread7.Start();
thread8.Start();
thread1.Join();
.
.
thread8.Join();
Thread thread1 = new Thread(() => bitmapRenderer.UpdateBitmap(0,height/8));
Thread thread2 = new Thread(() => bitmapRenderer.UpdateBitmap(height/8,2*height/8));
Thread thread3 = new Thread(() => bitmapRenderer.UpdateBitmap(2*height/8,3*height/8));
Thread thread4 = new Thread(() => bitmapRenderer.UpdateBitmap(3*height/8,4*height/8));
Thread thread5 = new Thread(() => bitmapRenderer.UpdateBitmap(4*height/8,5*height/8));
Thread thread6 = new Thread(() => bitmapRenderer.UpdateBitmap(5*height/8,6*height/8));
Thread thread7 = new Thread(() => bitmapRenderer.UpdateBitmap(6*height/8,7*height/8));
Thread thread8 = new Thread(() => bitmapRenderer.UpdateBitmap(7*height/8,height));

thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
thread5.Start();
thread6.Start();
thread7.Start();
thread8.Start();
thread1.Join();
.
.
thread8.Join();
There probably is a better way to create, start and join threads, but i wasn't able to find anything better. Its not clear to me how threads work overall. I have a 16 thread CPU and using 8 threads bumped the usage from 10% to 30%. How can i find out what a good number of threads to use is?
lock (bmp)
{
bmp.SetPixel(j,i,iterToColor(iterCount_temp));
}
lock (bmp)
{
bmp.SetPixel(j,i,iterToColor(iterCount_temp));
}
I had to lock the bitmap so that the threads wouldn't try to write at the same time. But i feel like this isn't the best practise as the threads will wait on one another fairly often. I wanted to save the X Y Color values in some structure and write all at once after joining, but was not yet able to come up with anything. Any ideas?
20 replies