Threaded Function Slows down the Main Thread

I’m working on a procedurally generated world engine and for some reasons, sometimes, the code that I run in the background create some lag spikes. This issue is no longer present if I decrease the amout of thread running in the backgroud. The function that I execute does not create any garbage and the profiler (even the deep one) dosen’t show any sign of spike. What could cause this issue? The code is huge, I can’t post it all unless I have some possible explanation

How many threads do you start? You shouldn’t have more worker thread than your CPU has cores. This is the general advice for any multi threading application. Any context switch on a CPU core is expensive. If you have a high workload your threads would need to run as long as possible. However if you have more high load realtime threads than there are cores, the OS has to time slice two or more threads on the same core. Any sort of background generating should be done by splitting the work into “tasks” and have a fix amount (less than there are CPU cores) of worker threads which simply pop a task from a queue.