E
E
Eugene Ordinary2020-07-31 03:31:35
C++ / C#
Eugene Ordinary, 2020-07-31 03:31:35

How to organize access of two threads to a common variable in C#?

Will there be a conflict between two threads when accessing the str variable? Need to take additional steps?

using System;
using System.Threading;

class Program
{
    static string str = "";  //  общая переменная

    static void Main(string[] args)
    {
        // создаем новый поток 1
        Thread myThread1 = new Thread(Writer1);
        myThread1.Start(); // запускаем поток

        // создаем новый поток 2
        Thread myThread2 = new Thread(Writer2);
        myThread2.Start(); // запускаем поток

        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine($"Thread0 str=: {str}");
            Thread.Sleep(350);
        }

        Console.ReadLine();
    }

    public static void Writer1()
    {
        for (int i = 0; i < 200; i++)
        {
            str = "Written by thread 1";
            Thread.Sleep(300);
        }
    }

    public static void Writer2()
    {
        for (int i = 0; i < 200; i++)
        {
            str = "Written by thread 2";
            Thread.Sleep(400);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
none7, 2020-07-31
@none7

In this particular case, no. The variable str is a pointer, from the point of view of the processor it is a primitive data type. The worst thing that could happen is a mess of bits in a variable, but the processor itself resolves such situations with primitive types. With structures, the same trick will not work.

R
Roman Mirilaczvili, 2020-07-31
@2ord

To avoid a race condition, use lock .
In the example, it would be worth removing Thread.Sleep for this to show up.

G
Geronom, 2020-07-31
@Geronom

It's better to use
static readonly object @lock = new object();
lock (@lock)
{
//Stuff
}
And there is a typo in public static void Writer2():
str = "Written by thread 1";
need
str = "Written by thread 2";
otherwise there will always be a conclusion with number 1 and confusion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question