how threads communicate with eachother? they dont use values of eachother, then what is the way of communication between them?
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: wait() notify() notifyAll()
Processes are typically independent of each other. Threads exist as the subset of a process. Threads can communicate with each other more easily than processes can.
All static and controlled data is shared between threads. All other data can also be shared through arguments/parameters and through based references, as long as the data is allocated and is not freed until all of the threads have finished using the data.
producer and consumer threads should capture each other's tid. producer on producing can send: pthread_kill(consumerID, SIGUSR1); consumer is setup with the signal handler for SIGUSR1, and can retrieve the produced result from the common std::queue saved by pthread_setspecific().
There are a few ways threads can communicate with each other. This list is not exhaustive, but does include the most used strategies.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With