In my program there is lot of loops that can be easily rewritten into multithread. Basically for each function which should be multithreadd I am writing following function:
void func_to_threaded(int i_from, int i_to, int num_th, ...other_parameters) { int i_min = i_from; int i_max = i_to; int i_inc = i_max / num_th; i_max = i_max % num_th + i_inc; thread* th_dens = new thread[num_th]; for (int i = 0; i < num_th; i++) { th_dens[i] = thread(func_one_thread, i_min, i_max, ...other_parameters); i_min = i_max; i_max += i_inc; } for (int i = 0; i < num_th; i++) th_dens[i].join(); delete[] th_dens; } Is there a way to rewrite this to be generic for every function of form
void func_one_thread(int i_min, int i_max, ...other_parameters)
i_fromis always 0. Tried mentally going through it with(3, 8, 2, ...), and ended up withthread(func_one_thread, 3, 4, ...)andthread(func_one_thread, 4, 8, ...). So, unless I missed something, it may be a bit uneven.i_fromis always zero and now I just tried to rewrite it more generally but failed...i_inc = (i_max - i_min) / num_th;would work. You'd need to check ifi_max - i_minwas cleanly divisible bynum_th, though, to see if any of the threads need to do extra work.i_max - i_minis not divisible bynum_threadthen the first thread is doing extra work - achieved by modnum_thread(%).