2010-08-13 3 views
7

스레드가 서로 통신하는 방법은 무엇입니까? 그들은 서로의 가치를 사용하지 않는다. 그러면 그들 사이의 의사 소통 방법은 무엇인가?스레드가 서로 통신하는 방법은 무엇입니까?

+0

, C#에서 어떻게 스레딩 작품 꽤 깊이있는 소개를 제공하는 무료 전자 책 여기를 확인 : [C# 스레딩에 대한 무료 전자 북] (http://www.albahari.com/threading/) – duesouth

답변

1

스레드는 값을 공유 할 수 있으며 그렇게 할 때주의해야합니다. .NET에서 가장 일반적인 메소드는 lock 문과 Interlocked 클래스입니다.

4

"그들은 서로의 값을 사용하지 않습니다"- 동일한 프로세스에서 두 개의 스레드가 잘 맞습니다. 은 공통 변수를 참조하십시오. 따라서 이것은 단순한 appraoch입니다. 그래서 우리는 조건을 기다리고 대기중인 스레드를 깨우기 위해 다양한 동기화, 잠금, mutices 및 sempahores를 사용합니다.

자바에서는 동기화와 같은 다양한 프리미티브를 사용합니다. 이것을 읽을 수 있습니다 tutorial

+0

+1이 사실을 고려하지 않은 이유를 이해할 수 없습니다. – Luca

5

스레드가 서로 통신 할 수있는 몇 가지 방법이 있습니다. 이 목록은 철저하지는 않지만 가장 많이 사용되는 전략을 포함합니다.

  • 공유 메모리 잠금 및 sempahores 같은 변수 또는 다른 데이터 구조 등
  • 동기화 프리미티브
  • ManualResetEvent 또는 AutoResetEvent

공유 메모리 등

  • 이벤트,

    public static void Main() 
    { 
        string text = "Hello World"; 
        var thread = new Thread(
        () => 
        { 
         Console.WriteLine(text); // variable read by worker thread 
        }); 
        thread.Start(); 
        Console.WriteLine(text); // variable read by main thread 
    } 
    

    동기화 프리미티브

    public static void Main() 
    { 
        var lockObj = new Object(); 
        int x = 0; 
        var thread = new Thread(
        () => 
        { 
         while (true) 
         { 
         lock (lockObj) // blocks until main thread releases the lock 
         { 
          x++; 
         } 
         } 
        }); 
        thread.Start(); 
        while (true) 
        { 
        lock (lockObj) // blocks until worker thread releases the lock 
        { 
         x++; 
         Console.WriteLine(x); 
        } 
        } 
    } 
    

    이벤트 이미 주어진 해답뿐만 아니라

    public static void Main() 
    { 
        var are = new AutoResetEvent(false); 
        var thread = new Thread(
        () => 
        { 
         while (true) 
         { 
         Thread.Sleep(1000); 
         are.Set(); // worker thread signals the event 
         } 
        }); 
        thread.Start(); 
        while (are.WaitOne()) // main thread waits for the event to be signaled 
        { 
        Console.WriteLine(DateTime.Now); 
        } 
    } 
    
  • +1

    +1에 대한 완전성. –

    관련 문제