Implement a thread safe FIFO queue

本文介绍了一种同步FIFO队列的实现方法,包括基本的读写操作,并通过两个测试案例验证了队列的功能。该队列支持阻塞直至可以返回一个值,遵循FIFO原则,且读写操作能并行进行。

/**
Implement a synchronized fifo queue - storage and two operations (read/write)
Read: Block until a value can be returned. (Optional Timeout). FIFO semantics. Remove first element and return it.
Write: If queue is full, wait (timeout). FIFO wait for other writers. Write element.
Reads and Writes should be able to happen in parallel.*/


public class Queue<T>
{
private int start = 0;
private int end = 0;
private int capacity = 0;

private Lock writeLock;


private T[] buffer;

private Queue(int capacity)
{
// check capacity for invalid case like negative value...

this.capacity = capacity;
buffer = new T[capacity];
}

// read
public T Dequeue()
{
while (start >= end)
{

}

lock (writeLock)
{
return this.buffer[start++];
}
}

// write
public bool Enqueue(T item)
{
while (end - start >= this.capacity)
{

}

lock (writeLock)
{
if (end >= this.capacity)
{
for (int i = 0; i <= end - start; i++)
{
this.buffer[i] = this.buffer[i + start];
}

end = end - start;
start = 0;
}

this.buffer[end++] = item;

return true;
}
}

// test case 1. : capacity = 3 E(1) E(2) E(3) E(4)
// E(1) -> [1] start = 0, end = 1
// E(2) -> [1, 2] start = 0, end = 2
// E(3) -> [1, 2, 3] start = 0, end = 3
// E(4) -> [1, 2, 3] start = 0, end = 3 return false;



// test case 2. : capacity = 3 E(1) E(2) E(3) D() E(4)
// E(1) -> [1] start = 0, end = 1
// E(2) -> [1, 2] start = 0, end = 2
// E(3) -> [1, 2, 3] start = 0, end = 3
// D() -> return 1, start = 1, end = 3
// E(4) -> [1, 2, 3] start = 1, end = 3 [2, 3, 4]
}

转载于:https://www.cnblogs.com/liangmou/p/8420644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值