在多核处理器的多个线程 [英] Multiple threads on a multicore processor
问题描述
如何在一个多线程的系统内核之间派发线程。 可以说,我有一个创建6个线程的程序。我的系统有3个核心。在这种情况下,将在线程的3个核心之间分配或将所有的线程相同的核心执行?
How are threads distributed between CORES in a multithreaded system. Lets say i have a program that creates 6 threads. My system has 3 CORES. In this case will the threads be distributed between the 3 COREs or will all the threads execute on the same CORE?
推荐答案
我发现这是一个体面的解释的博客文章。你可以使用一些的PInvoke调用来设置线程的亲和力:
I found a decent explanation on this blog post. You can use some pinvoke calls to set the thread affinity:
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
然后就可以使用这样的:
You can then use it like this:
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1 << processorNumber));
但你必须知道,托管线程可以从一个非托管的线程切换到另一个,和上方法适用于非托管线程,因此也不能保证它会工作100%。从上主题类:
这是操作系统的ThreadId没有固定的关系提高到一个管理 线程,因为非托管主机可以控制之间的关系 托管和非托管线程。具体而言,一个成熟的主机可以 使用CLR托管API来安排对很多托管线程 相同的操作系统线程,或者移动之间的托管线程 不同的操作系统线程。
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.
不过,你可以通过调用绕过这个 Thread.BeginThreadAffinity()
之前执行的PInvoke电话。
However you can circumvent this by calling Thread.BeginThreadAffinity()
before executing the pinvoke calls.
这篇关于在多核处理器的多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!