Skip to content

Instantly share code, notes, and snippets.

@jaredjenkins
Last active November 13, 2017 00:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredjenkins/5421892 to your computer and use it in GitHub Desktop.
Save jaredjenkins/5421892 to your computer and use it in GitHub Desktop.
Concurrent Queue for Unity
using System;
using System.Collections.Generic;
namespace PlaynomicsPlugin
{
internal class ConcurrentQueue<T>{
private readonly object syncLock = new object();
private Queue<T> queue;
public int Count
{
get
{
lock(syncLock)
{
return queue.Count;
}
}
}
public ConcurrentQueue()
{
this.queue = new Queue<T>();
}
public T Peek()
{
lock(syncLock)
{
return queue.Peek();
}
}
public void Enqueue(T obj)
{
lock(syncLock)
{
queue.Enqueue(obj);
}
}
public T Dequeue()
{
lock(syncLock)
{
return queue.Dequeue();
}
}
public void Clear()
{
lock(syncLock)
{
queue.Clear();
}
}
public T[] CopyToArray()
{
lock(syncLock)
{
if(queue.Count == 0)
{
return new T[0];
}
T[] values = new T[queue.Count];
queue.CopyTo(values, 0);
return values;
}
}
public static ConcurrentQueue<T> InitFromArray(IEnumerable<T> initValues)
{
var queue = new ConcurrentQueue<T>();
if(initValues == null)
{
return queue;
}
foreach(T val in initValues)
{
queue.Enqueue(val);
}
return queue;
}
}
}
@JannemanDev
Copy link

TryDequeue() method is missing. Any specific reason?

@JYKeith
Copy link

JYKeith commented Mar 4, 2016

This is not ConcurrentQueue.. but just queue + lock
See this. http://stackoverflow.com/questions/14111431/perfomance-of-concurrentqueue-vs-queue-lock

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment