Threadsafe collection without lock

后端 未结 5 2026
一个人的身影
一个人的身影 2020-12-13 00:59

I am preparing myself for an interview and I came across the followign question. I tried but I could not find anything which can create a class containing thread safe collec

5条回答
  •  攒了一身酷
    2020-12-13 01:50

    My solution. Basically mimic locking using Interlocked.Exchange and an AutoResetEvents. Did some simple tests and it seems working.

        public class SharedStringClass
        {
            private static readonly int TRUE = 1;
            private static readonly int FALSE = 0;
    
            private static int allowEntry;
    
            private static AutoResetEvent autoResetEvent;
    
            private IList internalCollection;
    
            public SharedStringClass()
            {
                internalCollection = new List();
                autoResetEvent = new AutoResetEvent(false);
                allowEntry = TRUE;
            }
    
            public void AddString(string strToAdd)
            {
                CheckAllowEntry();
    
                internalCollection.Add(strToAdd);
    
                // set allowEntry to TRUE atomically
                Interlocked.Exchange(ref allowEntry, TRUE);
                autoResetEvent.Set();
            }
    
            public string ToString()
            {
                CheckAllowEntry();
    
                // access the shared resource
                string result = string.Join(",", internalCollection);
    
                // set allowEntry to TRUE atomically
                Interlocked.Exchange(ref allowEntry, TRUE);
                autoResetEvent.Set();
                return result;
            }
    
            private void CheckAllowEntry()
            {
                while (true)
                {
                    // compare allowEntry with TRUE, if it is, set it to FALSE (these are done atomically!!)
                    if (Interlocked.CompareExchange(ref allowEntry, FALSE, TRUE) == FALSE)
                    {
                        autoResetEvent.WaitOne();
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
    

提交回复
热议问题