how threads communicate with eachother? they dont use values of eachother, then what is the way of communication between them?
We don't need Inter-process techniques for simple threads. The question seems mistaken in implying that variables are not shared between threads.
djna
2010-08-13 15:49:27
Somebody else added the "inter-process" tag. I can't see its relevance, so I've taken it off again.
Jon Hanna
2010-08-13 16:21:59
+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
2010-08-13 15:48:07
+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
orAutoResetEvent
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
2010-08-13 16:22:54
+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#: