DEV Community

Cover image for Local State vs Shared State
Mo
Mo

Posted on

Local State vs Shared State

Welcome back, everyone! Today, we're diving into an essential concept in C# programming: local state and shared state in threading. Understanding these concepts is crucial for writing efficient and safe multithreaded applications. ๐Ÿš€

Local State

Local state refers to variables confined to a single thread. These variables are not shared between threads, meaning each thread has its own copy. This isolation helps avoid conflicts since no other thread can modify these variables.

Shared State

A shared state involves variables accessible by multiple threads. When multiple threads access and modify the same variables, we must be cautious. Without proper synchronization, this can lead to race conditions where the outcome depends on the unpredictable timing of threads.

Example: Local State

Let's look at an example to illustrate the local state. Imagine we have two threads: a worker thread and a main thread. The worker thread will write "T1" 1000 times, while the main thread will write "MT" 1000 times. Here's a simple structure of how this works:

Thread thread1 = new Thread(Print);

thread1.Start("T");

Print("MT");

void Print(object? input)
{
    for (int index = 0; index < 1000; index++)
    {
        Console.Write(input);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, each thread operates independently, printing its respective message. Because there is a context switch between these two threads, you might see a mix of "T1" and "MT" in the output. ๐Ÿงตโžก๏ธ๐Ÿงต

Example: Shared State

Now, let's consider an example involving a shared state. We have a local variable index inside the Print method, and another variable isFinished outside of it. Here's the code snippet:

bool isFinished = false;

Print();

void Print()
{
    if (!isFinished)
    {
        isFinished = true;
    }

    for (int index = 0; index < 5; index++)
    {
        Console.Write("P ");
    }
}

new Thread(Print).Start();
Enter fullscreen mode Exit fullscreen mode

In this example, isFinished is a shared state variable. When the main thread sets isFinished to true, it affects the worker thread, causing it to break out of its loop. The output demonstrates how the shared state influences thread behaviour. โš ๏ธ

Conclusion

To sum up, the local state is easy to manage because each thread works with its own data, while the shared state requires careful synchronization to avoid race conditions. By understanding and properly managing these states, you can write efficient and safe multithreaded applications in C#.

If you found this explanation helpful, don't forget to like, subscribe, and hit the bell icon for more programming tutorials.
Thanks for reading and happy coding! ๐ŸŽ‰

Top comments (0)