views:

258

answers:

5

I am on Windows (Windows 7, XP and Vista). If I create a multi-threaded program, will the threads be executed on all available cores? Is it automatic? Is it guaranteed?

For example, if I have four threads and four processors, will the threads be executed one on each processor/core?

+3  A: 

They might. It depends on what other programs are running that may be utilizing the various cores as well, up to and including the OS.

In a nutshell, the OS should try to distribute threads pretty evenly, but trying to predict how and when each thread is placed on each core is an exercise in futility.

GWLlosa
+4  A: 

The operating system will decide based on thread state, priority, etc.

It is not guaranteed that the threads will all run on different processors. In fact, there are very few guarantees where thread execution order is concerned. They might all run on the same processor. They might all run in parallel, or they might not run at all. Not that this is likely, but you don't have any guarantees.

John Saunders
What's the problem with this one?
John Saunders
+1  A: 

Msdn about multiple processors explains how to force specific threads on specific processors. You normally rely on the operating system.

You could query the number of processors with GetSystemInfo.

foxx1337
+2  A: 

You may be interested to know that you can control which threads can run on which cores by using the SetThreadAffinityMask() function.

However, in virtually all cases it is best to let the OS manage the allocation of threads to cores. Only in very specific circumstances (such as if you are running high performance code that would be affected adversely by context switches and the resulting cache flush) should you ever need to manually set thread affinities.

Greg Hewgill
A: 

By default, all threads you create are eligable for execution on all cores of all CPUs. However, as your threads aren't the only threads in the computer, these cores are not available 100% of the time for your threads. Hence, the scheduler will give your threads a fair slice of avilable CPU power.

Since your threads can run everywhere , you will never encounter the situation that a core is doing nothing while your thread is waiting for another core to become available. And if you have 4 runnable threads on a 4 core machine, that means all cores will be busy. Note: a thread is not always runnable, e.g. if it's waiting on I/O.

MSalters