2014-11-14 5 views
0

을 사용하여 텍스트 파일에 쓰기를 바랍니다.이 one.i와 함께 나를 도울 수 있기를 바랍니다. C#으로 멀티 스레딩 프로그래밍 초보자입니다.멀티 스레드를 사용하여 C#

두 개의 스레드를 사용하여 두 개의 텍스트 파일에 범위 1에서 2000까지의 모든 숫자를 쓰는 프로그램을 작성하려고합니다.

모든 스레드는 "파일에 중복 된 숫자가 없습니다"라는 두 파일 중 하나에서 발견되지 않는 1에서 2000까지의 숫자를 써야하며 모든 스레드는 다른 스레드가 쓴 번호를 쓰지 않아야합니다. 끝에

우리는 우리가 여기에

2000 1에서 숫자를해야 두 파일의 수를 합병 내가 노력하고 소스 코드이지만 문제는 아래에서 루프에 대한 서면이있는 경우 이미지

나는 두 개의 동기화 된 스레드에 의해 쓰기의 과정을 처리 할 수 ​​없습니다와 나는 exception을했다 :

개체 동기화 방법은 코드의 동기화 블록에서 호출되었다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Threading; 

namespace Multithreading 
{ 
    class Program 
    { 

     static TextWriter file2 = new StreamWriter("file2 location"); 
     static TextWriter file1 = new StreamWriter("file1 location"); 

     static void Main(string[] args) 
     { 
      try 
      { 
       int[] array = new int[2000]; 
       Thread thread1 = new Thread(Program.writeinfile1); 
       Thread thread2 = new Thread(Program.writeinfile2); 

       for (int counter = 1; counter <= 2000; counter++) 
       { 
        thread1.Start(counter); 
        thread2.Start(++counter); 
        Monitor.Enter(thread1); 
        Monitor.Wait(thread1); 
        Monitor.PulseAll(thread2); 
       } 
      } 
      catch (FileNotFoundException) 
      { 
       Console.WriteLine("the file you are trying to open is not found"); 
      } 
     } 

     public static void writeinfile1(object x) 
     { 
      int converttointx = (int)x; 
      file1.WriteLine(converttointx); 
      file1.Close(); 
     } 

     public static void writeinfile2(object y) 
     { 
      int converttointy = (int)y; 
      file2.WriteLine(converttointy); 
      file2.Close(); 
     } 
    } 
} 
+0

나는이 숙제 가정? 어떻게 처리해야하는지에 대한 요구 사항이 있습니까? 왜냐하면 그렇지 않다면 루핑하고 각 루프에 2를 더하고 결과를 쓰는 것만 큼 간단합니다. –

+0

정확히 무엇이 문제입니까? 당신의 오류는 무엇입니까? 언제 깨지는거야? –

+0

결과가 파일에 기록되었지만 각 파일에 하나의 정수만 씁니다. 그러나 전체 루프를 완료하는 데 문제가 무엇인지 알지 못합니다. –

답변

1

여기가 일을 중복되지 않도록하기 위해 서로 이야기 멀티 스레드 호출의 예입니다. 나는 당신이 요구 한 것과 정확히 똑같은 일을하지 않았습니다. 당신은 제대로 Monitor 클래스를 사용하지 않는

using System; 
using System.Collections.Generic; 
using System.Threading; 
using System.Threading.Tasks; 

namespace StackOverflow 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      new Program(); 
      Console.WriteLine("done"); 
      Console.ReadKey(); 
     } 
     Program() 
     { 
      int noThreads = 5; 
      int target = 2000; 
      StartThread(noThreads, target); 
     } 

     //kicks off our threads/waits for all threads to complete before returning 
     void StartThread(int noThreads, int target) 
     { 
      int id = noThreads--; 
      if (id > 0) 
      { 
       Doer doer = new Doer(id, target); 
       Thread t = new Thread(doer.Do); 
       t.Start(); 
       StartThread(noThreads,target); 
       t.Join(); 
      } 
     } 


    } 

    class Doer 
    { 
     static int marker = 0; 
     static readonly object syncLocker = new object(); 
     readonly int id; 
     readonly int target; 

     public Doer(int id, int target) 
     { 
      this.id = id; 
      this.target = target; 
     } 

     public void Do() 
     { 
      while (marker < this.target) 
      { 
       int i; 
       lock (syncLocker) 
       { 
        i = ++marker; 
       } 
       System.Console.WriteLine("{0:00}: {1:###0}", id, i); 
       //Thread.Sleep(RandomNo()); //uncomment this & code below if your threads are taking turns/behaving too predictably 
      } 
     } 


     /* 
     static readonly Random rnd = new Random(); 
     static readonly object rndSyncLocker = new object(); 
     public static int RandomNo() 
     { 
      lock (rndSyncLocker) 
      { 
       return rnd.Next(0, 1000); 
      } 
     } 
     */ 

    } 
} 
0

그러나 희망이 ... 당신이 당신의 문제에 해결책을 파악하는 데 도움이 될 것입니다. Monitor.PulseAll(thread2);에 대한 호출은 within thread the thread which owns the lock이라고하며,이 경우 writeinfile1writeinfile2 메소드 내에 있어야합니다.

개체 동기화 방법은 코드의 동기화 블록에서 호출되었습니다

이것은 당신이 예외를 얻고있는 이유입니다.

은 올바른 방법에 대해 다음 StackOverflow의 질문이 Monitor.PulseAll(object)를 사용하는 참조 :

관련 문제