2011-12-09 13 views

答えて

11

設定スレッドの優先順位とスレッドアフィニティ

ワーカークラス

class PriorityTest 
{ 
    volatile bool loopSwitch; 
    public PriorityTest() 
    { 
     loopSwitch = true; 
    } 

    public bool LoopSwitch 
    { 
     set { loopSwitch = value; } 
    } 

    public void ThreadMethod() 
    { 
     long threadCount = 0; 

     while (loopSwitch) 
     { 
      threadCount++; 
     } 
     Console.WriteLine("{0} with {1,11} priority " + 
      "has a count = {2,13}", Thread.CurrentThread.Name, 
      Thread.CurrentThread.Priority.ToString(), 
      threadCount.ToString("N0")); 
    } 
} 

とテスト

class Program 
{ 

    static void Main(string[] args) 
    { 
     PriorityTest priorityTest = new PriorityTest(); 
     ThreadStart startDelegate = 
      new ThreadStart(priorityTest.ThreadMethod); 

     Thread threadOne = new Thread(startDelegate); 
     threadOne.Name = "ThreadOne"; 
     Thread threadTwo = new Thread(startDelegate); 
     threadTwo.Name = "ThreadTwo"; 

     threadTwo.Priority = ThreadPriority.Highest; 
     threadOne.Priority = ThreadPriority.Lowest; 
     threadOne.Start(); 
     threadTwo.Start(); 

     // Allow counting for 10 seconds. 
     Thread.Sleep(10000); 
     priorityTest.LoopSwitch = false; 

     Console.Read(); 
    } 
} 

ほとんどあなたがマルチコア・システムを持っている場合は、thread affinityを設定する必要があるかもしれませんもmsdnから取られたコード。本当の飢えを見るために、さらにスレッドを作成する必要があるかもしれません。

+4

良い例。 loopSwitchをvolatileとして宣言して、最適化の問題を防ぐことができます。 – Tudor

+1

助けてくれてありがとう! –

+1

コードにアフィニティを含めていません。マルチコアシステムでは、この例では、開始時に行を追加しないかぎり、両方のスレッドが10秒間実行されることを示しています(これは意図していません)。Process.GetCurrentProcess()。ProcessorAffinity =(System.IntPtr)1; (スレッドは最初のプロセッサでのみスケジューリング可能であることを指定します)。 – Virtlink

3

アプリケーションのスレッドアフィニティをタスクマネージャで設定し、1つのコアでのみ実行されるようにします。次に、優先順位の高いアプリケーションでビジー状態のスレッドを開始します。

+0

純粋なコーディングだけでこれを行う方法はありますか? (つまり、タスクマネージャの部分なし) –

+0

@Seanプロセスのプロパティを参照してください。http://msdn.microsoft.com/en-us/library/76yt3c0w.aspx –

関連する問題