局部变量是线程安全的吗? [英] Are local variables threadsafe?

查看:542
本文介绍了局部变量是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的课程:

I have a class like the one below:

class Program
    {
        static void Main(string[] args)
        {
            var outputWindow = new OutputWindow();

            var threads = new List<Thread>();

            Action action = () => outputWindow.Display(20);

            for (int i = 0; i < 10; i++)
            {
                var thread = new Thread(() => action()) {Name = "Thread " + i};
                threads.Add(thread);
            }

            foreach (var thread in threads)
            {
                thread.Start();
            }
        }
    }

    public class OutputWindow
    {
        public void Display(int x)
        {
            for (int i = 0; i < x; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " Outputcounter: " + i);
            }
        }
    }

问题是-该线程是否安全,是否会导致在显示方法内部的局部变量i出现任何竞争情况?所有线程都会按预期增加变量"i"的值(这是它增加值并且不会占用其他线程的i值)

Question is- is this thread safe and will this lead to any race condition on the local variable i inside the display method? Will all the threads increment the value of the variable "i" as expected(which is it increments the value and does not encroch into other threads value of i)

如果这是线程安全的,可以安全地假设在方法中声明的任何局部变量始终是线程安全的,而共享变量是需要同步的变量吗?

If this is threadsafe, will it be safe to assume that any local variables declared within a method is always thread safe and shared variables are the ones which needs synchronization?

谢谢, -迈克

推荐答案

每个方法调用将具有一组单独的局部变量.但是,这些变量可以引用其他方法也使用的对象.例如:

Each method invocation will have a separate set of local variables. However, those variables could refer to objects which other methods also use. For example:

public void AppendSomething(StringBuilder builder)
{
    builder.Append("Something");
}

这里builder仍然是局部变量(参数是局部变量),每次调用AppendSomething都会有一个独立的 variable -但您可以使用相同的线程从多个线程中调用该方法StringBuilder参考,因此该方法不是线程安全的. (因为StringBuilder不是线程安全的.)

Here builder is still a local variable (parameters are local variables) and each invocation of AppendSomething will have an independent variable - but you could call the method from multiple threads using the same StringBuilder reference, so that method is not thread-safe. (As StringBuilder isn't thread-safe.)

这篇关于局部变量是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆