Make a linked list thread safe

后端 未结 2 1234
花落未央
花落未央 2020-12-08 08:37

I know this has been asked before (and I will keep researching), but I need to know how to make a particular linked list function in a thread safe manner. My current issue i

2条回答
  •  情书的邮戳
    2020-12-08 09:21

    Here’s a quick example of how to use locks to synchronize your access to the list:

    private readonly IList elements = new List();
    
    public void ProcessElements()
    {
        lock (this.elements)
        {
            foreach (string element in this.elements)
                ProcessElement(element);
        }
    }
    
    public void AddElement(string newElement)
    {
        lock (this.elements)
        {
            this.elements.Add(element);
        }
    }
    

    A lock(o) statement means that the executing thread should acquire a mutual-exclusion lock on the object o, execute the statement block, and finally release the lock on o. If another thread attempts to acquire a lock on o concurrently (either for the same code block or for any other), then it will block (wait) until the lock is released.

    Thus, the crucial point is that you use the same object for all the lock statements that you want to synchronize. The actual object you use may be arbitrary, as long as it is consistent. In the example above, we’re declared our collection to be readonly, so we can safely use it as our lock. However, if this were not the case, you should lock on another object:

    private IList elements = new List();
    
    private readonly object syncLock = new object();
    
    public void ProcessElements()
    {
        lock (this.syncLock)
        {
            foreach (string element in this.elements)
                ProcessElement(element);
        }
    }
    
    public void AddElement(string newElement)
    {
        lock (this.syncLock)
        {
            this.elements.Add(element);
        }
    }
    

提交回复
热议问题