Jump to content
  • Advertisement
Sign in to follow this  
Kaze

[.net] Is my collection threadsafe?

This topic is 3686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What the title says, Is this a valid solution for a multi-threaded producer consumer problem
    public class Pipe<Type>
    {

        public Pipe() { 
        
        }
        Queue<Type> objs = new Queue<Type>();

        public void PushObject(Type obj) {
            lock (objs)
            {
                objs.Enqueue(obj);
            }
        }


        public Type[] GetObjects(int max)
        {
            lock (objs)
            {
                List<Type> list = new List<Type>();
                
                while (list.Count < max && objs.Count > 0){
                    list.Add(objs.Dequeue());
                }

                return list.ToArray();
            }
        }
    }


Share this post


Link to post
Share on other sites
Advertisement
Yeah, assuming this is the only place "objs" is being used. You can even move the list creation and return outside of the lock, leaving only the list.Add part.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!