<p>Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this?</p>

<p>And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows?</p>

[{'answer_id': 32347, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 2, 'selected': False, 'text': '<p>Where each thread goes is generally handled by the OS itself...so generate 4 threads on a 4 core system and the OS will decide which cores to run each on, which will usually be 1 thread on each core.</p>\n'}, {'answer_id': 32348, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 7, 'selected': True, 'text': '<p>Don\'t bother doing that.</p>\n\n<p>Instead use the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" rel="noreferrer">Thread Pool</a>. The thread pool is a mechanism (actually a class) of the framework that you can query for a new thread.</p>\n\n<p>When you ask for a new thread it will either give you a new one or enqueue the work until a thread get freed. In that way the framework is in charge on deciding wether it should create more threads or not depending on the number of present CPUs.</p>\n\n<p>Edit: In addition, as it has been already mentioned, the OS is in charge of distributing the threads among the different CPUs.</p>\n'}, {'answer_id': 32352, 'author': 'wvdschel', 'author_id': 2018, 'author_profile': 'https://Stackoverflow.com/users/2018', 'pm_score': 2, 'selected': False, 'text': "<p>It is the operating system's job to split threads across different cores, and it will do so when automatically when your threads are using a lot of CPU time. Don't worry about that. As for finding out how many cores your user has, try <code>Environment.ProcessorCount</code> in C#.</p>\n"}, {'answer_id': 32359, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 2, 'selected': False, 'text': "<p>You shouldn't have to worry about doing this yourself.  I have multithreaded .NET apps running on dual-quad machines, and no matter how the threads are started, whether via the ThreadPool or manually, I see a nice even distribution of work across all cores.</p>\n"}, {'answer_id': 32410, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 1, 'selected': False, 'text': "<p>One of the reasons you should not (as has been said) try to allocated this sort of stuff yourself, is that you just don't have enough information to do it properly, particularly into the future with NUMA, etc.   </p>\n\n<p>If you have a thread read-to-run, and there's a core idle, the kernel <em>will</em> run your thread, don't worry.</p>\n"}, {'answer_id': 32477, 'author': 'Peter Meyer', 'author_id': 1875, 'author_profile': 'https://Stackoverflow.com/users/1875', 'pm_score': 3, 'selected': False, 'text': '<p>In the case of managed threads, the complexity of doing this is a degree greater than that of native threads.  This is because CLR threads are not directly tied to a native OS thread.  In other words, the CLR can switch a <em>managed</em> thread from native thread to native thread as it sees fit.  The function <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.beginthreadaffinity.aspx" rel="noreferrer">Thread.BeginThreadAffinity</a> is provided to place a managed thread in lock-step with a native OS thread.  At that point, you could experiment with using native API\'s to give the underlying native thread processor affinity.  As everyone suggests here, this isn\'t a very good idea.  In fact there is <a href="http://msdn.microsoft.com/en-us/library/ms686247.aspx" rel="noreferrer">documentation</a> suggesting that threads can receive less processing time if they are restricted to a single processor or core.</p>\n\n<p>You can also explore the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process(VS.80).aspx" rel="noreferrer">System.Diagnostics.Process</a> class.  There you can find a function to enumerate a process\' threads as a collection of <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processthread(VS.80).aspx" rel="noreferrer">ProcessThread</a> objects.  This class has methods to set ProcessorAffinity or even set a <em>preferred</em> processor -- not sure what that is.</p>\n\n<p>Disclaimer: I\'ve experienced a similar problem where I thought the CPU(s) were under utilized and researched a lot of this stuff; however, based on all that I read, it appeared that is wasn\'t a very good idea, as evidenced by the comments posted here as well.  However, it\'s still interesting and a learning experience to experiment.</p>\n'}, {'answer_id': 568002, 'author': 'Joe Erickson', 'author_id': 56710, 'author_profile': 'https://Stackoverflow.com/users/56710', 'pm_score': 4, 'selected': False, 'text': '<p>It is not necessarily as simple as using the thread pool. </p>\n\n<p>By default, the thread pool allocates multiple threads for each CPU. Since every thread which gets involved in the work you are doing has a cost (task switching overhead, use of the CPU\'s very limited L1, L2 and maybe L3 cache, etc...), the optimal number of threads to use is &lt;= the number of available CPU\'s - unless each thread is requesting services from other machines - such as a highly scalable web service. In some cases, particularly those which involve more hard disk reading and writing than CPU activity, you can actually be better off with 1 thread than multiple threads.</p>\n\n<p>For most applications, and certainly for WAV and MP3 encoding, you should limit the number of worker threads to the number of available CPU\'s. Here is some C# code to find the number of CPU\'s:</p>\n\n<pre><code>int processors = 1;\nstring processorsStr = System.Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");\nif (processorsStr != null)\n    processors = int.Parse(processorsStr);\n</code></pre>\n\n<p>Unfortunately, it is not as simple as limiting yourself to the number of CPU\'s. You also have to take into account the performance of the hard disk controller(s) and disk(s). </p>\n\n<p>The only way you can really find the optimal number of threads is trial an error. This is particularly true when you are using hard disks, web services and such. With hard disks, you might be better off not using all four processers on you quad processor CPU. On the other hand, with some web services, you might be better off making 10 or even 100 requests per CPU.</p>\n'}, {'answer_id': 11085871, 'author': 'Amit Puri', 'author_id': 1464088, 'author_profile': 'https://Stackoverflow.com/users/1464088', 'pm_score': 2, 'selected': False, 'text': '<p>you cannot do this, as only operating system has the privileges to do it. If you will decide it.....then it will be difficult to code applications. Because then you also need to take care for inter-processor communication. critical sections. for each application you have to create you own semaphores or mutex......to which operating system gives a common solution by doing it itself.......</p>\n'}, {'answer_id': 18499947, 'author': 'Mantosh Kumar', 'author_id': 2724703, 'author_profile': 'https://Stackoverflow.com/users/2724703', 'pm_score': 3, 'selected': False, 'text': '<p>You can definitely do this by writing the routine inside your program.</p>\n\n<p>However you should not try to do it, since the Operating System is the best candidate to manage these stuff. I mean user mode program should not do try to do it.</p>\n\n<p>However, sometimes, it can be done (for really advanced user) to achieve the load balancing and even to find out true multi thread multi core problem (data racing/cache coherence...) as different threads would be truly executing on different processor. </p>\n\n<p>Having said that, if you still want to achieve we can do it in the following way. I am providing you the pseudo code for(Windows OS), however they could easily be done on Linux as well.</p>\n\n<pre><code>#define MAX_CORE 256\nprocessor_mask[MAX_CORE] = {0};\ncore_number = 0;\n\nCall GetLogicalProcessorInformation();\n// From Here we calculate the core_number and also we populate the process_mask[] array\n// which would be used later on to set to run different threads on different CORES.\n\n\nfor(j = 0; j &lt; THREAD_POOL_SIZE; j++)\nCall SetThreadAffinityMask(hThread[j],processor_mask[j]);\n//hThread is the array of handles of thread.\n//Now if your number of threads are higher than the actual number of cores,\n// you can use reset the counters(j) once you reach to the "core_number".\n</code></pre>\n\n<p>After the above routine is called, the threads would always be executing in the following manner:</p>\n\n<pre><code>Thread1-&gt; Core1\nThread2-&gt; Core2\nThread3-&gt; Core3\nThread4-&gt; Core4\nThread5-&gt; Core5\nThread6-&gt; Core6\nThread7-&gt; Core7\nThread8-&gt; Core8\n\nThread9-&gt; Core1\nThread10-&gt; Core2\n...............\n</code></pre>\n\n<p>For more information, please refer to manual/MSDN to know more about these concepts.</p>\n'}, {'answer_id': 29392050, 'author': 'AlexDev', 'author_id': 733760, 'author_profile': 'https://Stackoverflow.com/users/733760', 'pm_score': 4, 'selected': False, 'text': '<p>Although I agree with most of the answers here, I think it\'s worth it to add a new consideration: Speedstep technology.</p>\n\n<p>When running a CPU intensive, single threaded job on a multi-core system, in my case a Xeon E5-2430 with 6 real cores (12 with HT) under windows server 2012, the job got spread out among all the 12 cores, using around 8.33% of each core and never triggering a speed increase. The CPU remained at 1.2 GHz.</p>\n\n<p>When I set the thread affinity to a specific core, it used ~100% of that core, causing the CPU to max out at 2.5 GHz, more than doubling the performance.</p>\n\n<p>This is the program I used, which just loops increasing a variable. When called with -a, it will set the affinity to core 1. The affinity part was based on <a href="http://blog.rebuildall.net/2010/03/08/Running_NET_threads_on_selected_processor_cores" rel="noreferrer">this post</a>.</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace Esquenta\n{\n    class Program\n    {\n        private static int numThreads = 1;\n        static bool affinity = false;\n        static void Main(string[] args)\n        {\n            if (args.Contains("-a"))\n            {\n                affinity = true;\n            }\n            if (args.Length &lt; 1 || !int.TryParse(args[0], out numThreads))\n            {\n                numThreads = 1;\n            }\n            Console.WriteLine("numThreads:" + numThreads);\n            for (int j = 0; j &lt; numThreads; j++)\n            {\n                var param = new ParameterizedThreadStart(EsquentaP);\n                var thread = new Thread(param);\n                thread.Start(j);\n            }\n\n        }\n\n        static void EsquentaP(object numero_obj)\n        {\n            int i = 0;\n            DateTime ultimo = DateTime.Now;\n            if(affinity)\n            {\n                Thread.BeginThreadAffinity();\n                CurrentThread.ProcessorAffinity = new IntPtr(1);\n            }\n            try\n            {\n                while (true)\n                {\n                    i++;\n                    if (i == int.MaxValue)\n                    {\n                        i = 0;\n                        var lps = int.MaxValue / (DateTime.Now - ultimo).TotalSeconds / 1000000;\n                        Console.WriteLine("Thread " + numero_obj + " " + lps.ToString("0.000") + " M loops/s");\n                        ultimo = DateTime.Now;\n                    }\n                }\n            }\n            finally\n            {\n                Thread.EndThreadAffinity();\n            }\n        }\n\n        [DllImport("kernel32.dll")]\n        public static extern int GetCurrentThreadId();\n\n        [DllImport("kernel32.dll")]\n        public static extern int GetCurrentProcessorNumber();\n        private static ProcessThread CurrentThread\n        {\n            get\n            {\n                int id = GetCurrentThreadId();\n                return Process.GetCurrentProcess().Threads.Cast&lt;ProcessThread&gt;().Single(x =&gt; x.Id == id);\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>And the results:</p>\n\n<p><img src="https://i.stack.imgur.com/3CLOs.png" alt="results"></p>\n\n<p>Processor speed, as shown by Task manager, similar to what CPU-Z reports:</p>\n\n<p><img src="https://i.stack.imgur.com/MALln.png" alt="enter image description here"></p>\n'}]
['https://Stackoverflow.com/questions/32343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2577/']