Really dumb and basic question about threads vs processes

What happens when a single process runs more threads than the CPU has? The scenario is that I have a process scanning two directories for matching files. OS is Windows 11. The program can have the user device how many threads to give to each directory scan. I have decided to allocate 8 threads to each directory scan, so 16 threads in total for the process. The CPU has 8 cores and 16 threads in total. What would happen if the process was allocated 32 threads, for example? Windows would schedule it... but how? Since these threads are perfectly fungible (they all are performing the exact same task), how would Windows decide which threads should be given priority, and on what basis? What happens to the other 16 threads? Paused entirely? Execution is alternated so half are paused, the others are executed, and then vice versa?
 

rain shadow

Ars Tribunus Angusticlavius
6,682
Subscriptor++
The threads will most likely be waiting on I/O most of the time. When one thread enters a wait, the OS may take the processor core that was servicing it and assign it to another thread for a while. These pause/run decisions will not necessarily be grouped by the OS in any way that makes sense. It is doubtful that whatever drive you are using can service 32 threads any faster than 2 or 3.

You can create thousands of threads. A few will run and make progress, the OS may swap other threads in and out, and others will run and make some progress. Eventually the task will complete.

What I usually do is run tests with 1, 2, 4, 8, 16 etc threads and time the results. Usually there is a point where you have so many threads that it's actually slower than using fewer threads. Then zero in on the best number (e.g. if 4 was the best and 8 was only slightly slower, try 5, 6, 7) You may have to run the tests multiple times to get a good enough average to overcome run-to-run variance.

Using tons of threads can help by making things actually worse so that you have an easier time spotting race conditions, deadlocks, bottlenecks, etc.
 
The threads will most likely be waiting on I/O most of the time. When one thread enters a wait, the OS may take the processor core that was servicing it and assign it to another thread for a while. These pause/run decisions will not necessarily be grouped by the OS in any way that makes sense. It is doubtful that whatever drive you are using can service 32 threads any faster than 2 or 3.
It's a ZFS RAID array with 12 spindles. With Windows Server, the default is 20 threads per queue. Not sure what it is for TrueNAS though. But number of spindles obviously doesn't give any indication of how many threads can be effective simultaneously. ZFS can't give any guarantees about where any particular piece of data is physically located: I could just be incredibly unlucky and all the blocks for all 16 files that my threads are trying to access are all on the same physical drive. :p
https://docs.microsoft.com/en-us/window ... ile-server

You can create thousands of threads. A few will run and make progress, the OS may swap other threads in and out, and others will run and make some progress. Eventually the task will complete.

What I usually do is run tests with 1, 2, 4, 8, 16 etc threads and time the results. Usually there is a point where you have so many threads that it's actually slower than using fewer threads. Then zero in on the best number (e.g. if 4 was the best and 8 was only slightly slower, try 5, 6, 7) You may have to run the tests multiple times to get a good enough average to overcome run-to-run variance.

Using tons of threads can help by making things actually worse so that you have an easier time spotting race conditions, deadlocks, bottlenecks, etc.
Thanks. This is great background information. I wasn't actually interested in increasing performance, this was more of an academic question so that I can understand what is going on, but having guidance on performance tuning certainly is helpful. I can try running benchmarks at some point, just to see what would be the optimal number of threads for my particular workload.
 

rain shadow

Ars Tribunus Angusticlavius
6,682
Subscriptor++
this was more of an academic question so that I can understand what is going on
Multithreading is IMHO a very rich topic, with lots of interesting subtopics, covered by plenty of books and articles. It's interesting to write and use multithreaded programs, there is a wide variety of multithreading API's, and stepping back and learning about parallelism in general is delightful.

I learned mostly by reading unix man pages on pthreads, and from the book https://www.amazon.com/How-Write-Parall ... 026203171X

Debugging threaded programs and learning what non-thread-safe-functions/practices to avoid is a toughie. It was probably a decade before I actually got to the point where I felt like I could reasonably debug random bits of code for thread-safety issues.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,353
Subscriptor++
What happens when a single process runs more threads than the CPU has? The scenario is that I have a process scanning two directories for matching files. OS is Windows 11. The program can have the user device how many threads to give to each directory scan. I have decided to allocate 8 threads to each directory scan, so 16 threads in total for the process. The CPU has 8 cores and 16 threads in total. What would happen if the process was allocated 32 threads, for example? Windows would schedule it... but how? Since these threads are perfectly fungible (they all are performing the exact same task), how would Windows decide which threads should be given priority, and on what basis? What happens to the other 16 threads? Paused entirely? Execution is alternated so half are paused, the others are executed, and then vice versa?

Generally speaking, there are two kinds of processes in this CPU bound, and IO bound. Since you are doing IO, this process is probably IO bound. That means that the threads spend most of their time blocked waiting on the IO subsystems to give them data to process. So, most of the time, all 32 threads are paused entirely while waiting for the IO requests to return.

This is why IO bound processes tend to preform well with many many threads. The limit at hand being the bandwidth and latency. If those are large enough, it can be worthwhile to have hundreds of threads. (For spinning disks, they can typically service one request at a time, so, if you are accessing one, you want n+1 threads where n is the number of disks, or to use asynchronous IO) Your processor, on the other hand, will be mostly idle.

For CPU bound tasks, given an eight core processor, with hyperthreading*, the operating system can schedule up to 16 threads for simultaneous execution, meaning you want as many threads as there are logical processors in the system. Any extra threads (say from other processes or ready io threads) will be paused waiting for the operating system to preform a context switch.

Threads are generally scheduled for blocks of time known as quantums; so, normally, a thread will be permitted to run uninterrupted for a quantum or three (somewhere between 30 and a few hundred ms) or until some device receives input and interrupts the processor. Then the timer on that core will run out, the executing thread will be interrupted, and control will be returned to the scheduler which, if there is another ready thread of the same priority, will save off the context and schedule the next ready thread.

In Windows, ready threads are scheduled in a round robin fashion by priority. So, higher priority threads are always scheduled before lower priority threads, and threads with a given priority are scheduled one after another in a cycle. If a higher priority thread becomes ready, the lower priority thread will be preempted and the higher priority thread permitted to run. If a thread is a thread for the foreground process, it gets scheduled for three times as long as threads for background processes do.

* Hyperthreading allows each core to switch back and forth between two threads of execution, interleaving their operations to allow for things like more efficient branch prediction and dealing with other timing based issues that might otherwise cause for parts of the core to starve for work while waiting for an operation to complete.

(For way too much information about windows scheduling, https://www.microsoftpressstore.com/art ... ?p=2233328 is an interesting article).
 
D

Deleted member 43669

Guest
Also I'm curious as to what you're doing. I assume you're doing recursive scans? Or are you doing some kind of "scan for new files"? I doubt it's the latter, but in that case, there are APIs that will do it for you under certain conditions.

(This also got me thinking about that Windirstat alternative that came out recently that is *magically* fast...)
 
Thanks all, great info.

Also I'm curious as to what you're doing. I assume you're doing recursive scans? Or are you doing some kind of "scan for new files"? I doubt it's the latter, but in that case, there are APIs that will do it for you under certain conditions.

(This also got me thinking about that Windirstat alternative that came out recently that is *magically* fast...)
I have a local data set and what should be the same data which is a restore from a cloud backup. Just verifying that they are indeed identical. Both sets are stored on different SMB shares. I'm using FreeFileSync to do the comparison.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
This is why IO bound processes tend to preform well with many many threads. The limit at hand being the bandwidth and latency. If those are large enough, it can be worthwhile to have hundreds of threads. (For spinning disks, they can typically service one request at a time, so, if you are accessing one, you want n+1 threads where n is the number of disks, or to use asynchronous IO) Your processor, on the other hand, will be mostly idle.
This is woefully pessimistic, and not reflective of modern hardware or OS implementation. Spinning disks will keep a queue of pending requests, and service them as quickly as possible on the whole. That means that if it has requests for blocks on tracks 10, 50, and 20, it will probably try to be smart and return them in an order that minimizes total seeking and rotational delay. To do that, it need multiple threads making independent requests for each spindle, so that there's flexibility to actually provide the best possible throughput.
 

Jehos

Ars Legatus Legionis
55,560
This is why IO bound processes tend to preform well with many many threads. The limit at hand being the bandwidth and latency. If those are large enough, it can be worthwhile to have hundreds of threads. (For spinning disks, they can typically service one request at a time, so, if you are accessing one, you want n+1 threads where n is the number of disks, or to use asynchronous IO) Your processor, on the other hand, will be mostly idle.
This is woefully pessimistic, and not reflective of modern hardware or OS implementation. Spinning disks will keep a queue of pending requests, and service them as quickly as possible on the whole. That means that if it has requests for blocks on tracks 10, 50, and 20, it will probably try to be smart and return them in an order that minimizes total seeking and rotational delay. To do that, it need multiple threads making independent requests for each spindle, so that there's flexibility to actually provide the best possible throughput.
Counterpoint, adding an abstraction there (it can handle multiple threads) may or may not be useful depending on how predictable you expect your I/O to be. What you're describing will sometimes go faster than the treat-each-disk-like-single-threaded architecture, but other times it will fall over and be very slow. That could be a problem, depending on the application.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
I think it more depends on how much you want to optimize for system throughput versus fairness/progress of the individual threads. If you want the best throughput, you'll expose as many of the requests as possible up front, and schedule them in bulk without regard to thread prioritization. And yeah, that sort of scheduling has to happen in the OS, deciding which requests to actually present to the disk controller in what order.
 

rain shadow

Ars Tribunus Angusticlavius
6,682
Subscriptor++
deciding which requests to actually present to the disk controller in what order.
Data-point-ish anecdote.

We got some code that was new and slow and written by 3rd party. Boss wanted me to tune it.

It was accessing random spots in a modest file, maybe 1GB or so, but it was 2005 so the randomness was enough to throw the OS file cache and the disk cache for a loop. Every access was cache miss, a seek, and rotation delay.

So what I did was collect groups of these random but related accesses together, sorted them, and then presented the read requests to the os in order. It was a solid 30% improvement.

The code is still in there, but probably makes almost no difference these days when using an SSD or on a system with enough memory to cache the whole file.
 

tiosteven

Ars Tribunus Militum
1,743
I manage large DB systems. One important thing to decide is if you are expecting fast latency response or maximum throughput. They require different tuning.

If the former, low latency, for the most point you'll want to keep the number of "waiting to do something" threads to be somewhat fewer than the number of available threads. (Basically load on *nix systems.) Queue theory is brutal once a high cpu thread system approaches the knee. "Things look good-- oh, system down."

For the latter, for i/o bound processes, it is much more dependent on the i/o subsystem. As an example, I have a production system in AWS with 24 cores but a 6 thread backup easily maxes out the bandwidth limitation imposed by the instance type. Really good for an oltp system but we have to keep an eye out for deployments creating a batch like functionality.

I don't know much about cpu bound workloads. I do know you can get crazy speedups or slowdowns based on how much of the code/data set fits in the various l* caches. Sorry i don't remember the link, but I'm thinking about a fizz/buzz competition where the compute thread stayed in l1/2 as much as possible and a second thread focused on moving the l2 output to general memory. It was at least 4x as fast as other implementations that ignored the l cache boundaries.

Like most parallel processing questions, it's complicated. Beyond all the normal but not trivial logical consistency issues, you have more non-obvious ways to hit resource limits as well.
 

Jehos

Ars Legatus Legionis
55,560
I come squarely from the world of supercomputing. The definition of a supercomputer is a device for turning compute-bound problems into IO-bound problems. Of course, we're not very good at using them efficiently, so most of the problems stay compute-bound anyway.
You mean they're not just excuses to do multi-rack artwork designs? o_O