tags:

views:

117

answers:

4

how threads communicate with eachother? they dont use values of eachother, then what is the way of communication between them?

+6  A: 

Pipes, Shared Memory, Sockets, Delegates...

See this link.

James
We don't need Inter-process techniques for simple threads. The question seems mistaken in implying that variables are not shared between threads.
djna
Somebody else added the "inter-process" tag. I can't see its relevance, so I've taken it off again.
Jon Hanna
+3  A: 

"they don't use values of each other" - well two threads in the same process can see common variables, so that's the simples appraoch. So we use various synchronization, locking, mutices and sempahores to wait for conditions and wake up waiting threads.

In Java you use various primitives such as synchronization. You could read this tutorial

djna
+1 I don't understand why this fact is not considered.
Luca
+2  A: 

There are a few ways threads can communicate with each other. This list is not exhaustive, but does include the most used strategies.

  • Shared memory, like a variable or some other data structure
  • Synchronization primitives, like locks and sempahores
  • Events, like ManualResetEvent or AutoResetEvent

Shared memory

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
}

Synchronization primitives

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);
    }
  }
}

Events

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);
  }
}
Brian Gideon
+1 for completeness.
Marty Pitt
+1  A: 

In addition to the answers already given, check here for a free e-book giving quite an in-depth introduction to how threading works in C#:

Free e-book on C# Threading

I second that recommendation.
Brian Gideon