C#互锁用作锁定机制吗? [英] C# Interlocked functions as a lock mechanism?

查看:301
本文介绍了C#互锁用作锁定机制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读有关ReaderWriterLockSlim锁定机制的信息时,有一个家伙建议Interlock函数可以用于更好的锁定

While I was reading about ReaderWriterLockSlim lock mechanism , There was this guy who suggested that Interlock Functions can be used for a finer locking

此外,我在此处找到了马克的另一个答案:

Also, I found here another answer from Marc :

...写入将其更改为克隆副本,然后使用 Interlocked.CompareExchange交换引用(重新应用它们 如果在此期间另一个线程更改了引用,则更改).

...Writes make their change to a cloned copy, then use Interlocked.CompareExchange to swap the reference (re-applying their change if another thread mutated the reference in the interim).

好,目前我对Interlocked对象的了解仅是,它用于(在多线程环境中)执行原子additionscomparecompareExchange原子操作. (而且我知道如何使用它)

Well , Currently all I know about Interlocked object , is that it is used (in a multithreaded environment) to do atomic additions, compare , compareExchange operations. (and I know how to use it)

但是(这是我的问题)—

问题

如何将其用作? (示例代码将不胜感激)

How can I use it as a lock ? ( sample code will be much appreciated)

为简单起见,我粘贴了这段代码(这不是线程安全的-如果Go同时被两个线程调用,则可能会出现除以零的错误 ):

For simplicity , I'm pasting this code ( which is not thread safe - if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error) :

class ThreadUnsafe
 {
   static int _val1 = 1, _val2 = 1;

   static void Go()
       {
        if (_val2 != 0) Console.WriteLine (_val1 / _val2);
        _val2 = 0;
       }
}

我如何使用互锁来替换锁(这将解决问题)?

How can I use Interlock to replace the lock (which would have solved the problem) ?

推荐答案

Interlocked用于实现无锁算法和数据结构.因此,它不是更精细的锁定",甚至根本不是锁定.它使您可以在多线程环境中安全地进行小的且定义明确的操作:例如,如果您希望两个线程递增同一变量,则可以使用Interlocked代替获取重量级锁并使用常规增量".

Interlocked is used to implement lockless algorithms and data structures. It's therefore not "finer locking", or even locking at all. It lets you do small and well-defined operations safely in a multi-threaded environment: for instance, if you want two threads to increment the same variable, you can use Interlocked to do it instead of acquiring a heavyweight lock and using the "regular increment".

但是,在常规锁下,您可以使用Interlocked做很多很多事情.例如,任何涉及原子地修改多个变量的操作通常都无法通过Interlocked完成,因此您将无法在示例中使用它.

However, there are many, many things that you can't do with Interlocked that you could do under a regular lock. For instance, anything that involves modifying more than one variable atomically generally can't be done with Interlocked, so you wouldn't be able to use it for your example.

Interlocked可以帮助开发人员实现锁定机制,尽管您也可以使用内置的锁定机制.大多数锁都需要内核支持才能中断被阻塞的线程,直到该锁可用为止.因此,您只能单独使用Interlocked实现的一种锁是自旋锁:一种线程会不断尝试获取的锁,直到它起作用为止.

Interlocked can, however, help developers implement locking mechanism, though you might as well use the built-in ones. Most locks require kernel support to interrupt the blocked thread until the lock becomes available. Therefore, the only kind of lock that you can implement with Interlocked alone is a spin lock: a lock that threads continually try to acquire until it works.

class InterlockedLock
{
    private int locked;

    public void Lock()
    {
        while (Interlocked.CompareExchange(ref locked, 1, 0) != 0)
            continue; // spin
    }

    public void Unlock()
    {
        locked = 0;
    }
}

在此示例中,locked最初为零.当某个线程首次尝试获取它时,locked变为1,随后的尝试访问Lock的线程将旋转,直到有人调用Unlock再次使locked 0为止.

In this example, locked is initially zero. When a thread tries to acquire it for the first time, locked becomes 1, and subsequent threads trying to Lock it will spin until someone calls Unlock to make locked 0 again.

这篇关于C#互锁用作锁定机制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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