从多个线程访问这个变量是否安全? [英] Is it safe to access this variable from multiple threads?

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

问题描述

我通常按照以下方式编写代码:

I commonly write code that is along these lines:

public class MyClass
{
    static bool m_stop = false;

    public static void Main()
    {
        var th = new Thread(DoStuff);

        th.Start();

        Console.ReadLine();

        m_stop = true;

        th.Join();
    }

    private static void DoStuff()
    {
        while( !m_stop )
        {
            // do things here
        }
    }
}

... 我总是同步访问变量 m_stop,只是出于习惯.我想知道是否真的有必要这样做(假设在 DoStuff() 中运行一两个额外的循环不会有任何伤害).如果代码完全像这样执行,可能发生的最坏情况是什么?我曾想过为 m_stop 使用 volatile 关键字,但我不确定这是否必要.有人确定吗?

... and I always synchronize access to the variable m_stop, just out of habit. I'm wondering whether it's actually necessary to do that (assuming running an extra loop or two in DoStuff() won't hurt anything). What is the worst that could happen if the code executed exactly like this? I've toyed with the thought of using the volatile keyword for m_stop, but I'm not sure that even that is necessary. Anyone know for sure?

推荐答案

在没有易失性和任何同步的情况下,您展示的代码不是线程安全的.一个线程可以更改变量的值,而另一个线程可能永远看到它,永远循环.如果你用一个公共锁同步所有对它的访问,它是线程安全的.

Without being volatile and without any synchronization, the code that you've shown isn't thread-safe. One thread could change the value of the variable and the other thread might never see it, looping forever. If you synchronize all access to it with a common lock, it is thread-safe.

现在波动性是一个棘手的话题 - 我以为我直到最近才理解它,但它并不像我想象的那样.但是,我很确定只要让变量 volatile 就可以满足您的需求.

Now volatility is a tricky topic - I thought I understood it until recently, but it doesn't mean quite what I thought it did. However, I'm pretty sure that just making the variable volatile will do what you need it to.

对于更复杂的事情,我通常使用完全同步:每次访问共享数据时都取出一个锁.

For anything more complicated, I'd usually use full synchronization: take out a lock every time you access the shared data.

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

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