【发布时间】:2011-03-21 01:47:51
【问题描述】:
我正在尝试编写一个管理 3 个流的缓冲区管理器。典型的用法是慢速生产者和快速消费者。三个缓冲区背后的想法是,生产者总是有一个缓冲区要写入,而消费者总是得到最新的数据。
现在我已经有了这个,它可以正常工作了。
namespace YariIfStream
{
/// <summary>
/// A class that manages three buffers used for IF data streams
/// </summary>
public class YariIFStream
{
private Stream writebuf; ///<value>The stream used for writing</value>
private Stream readbuf; ///<value>The stream used for reading</value>
private Stream swapbuf; ///<value>The stream used for swapping</value>
private bool firsttime; ///<value>Boolean used for checking if it is the first time a writebuffers is asked</value>
private Object sync; ///<value>Object used for syncing</value>
/// <summary>
/// Initializes a new instance of the Yari.YariIFStream class with expandable buffers
/// </summary>
public YariIFStream()
{
sync = new Object();
eerste = true;
writebuf = new MemoryStream();
readbuf = new MemoryStream();
swapbuf = new MemoryStream();
}
/// <summary>
/// Returns the stream with the buffer with new data ready to be read
/// </summary>
/// <returns>Stream</returns>
public Stream GetReadBuffer()
{
lock (sync)
{
Monitor.Wait(sync);
Stream tempbuf = swapbuf;
swapbuf = readbuf;
readbuf = tempbuf;
}
return readbuf;
}
/// <summary>
/// Returns the stream with the buffer ready to be written with data
/// </summary>
/// <returns>Stream</returns>
public Stream GetWriteBuffer()
{
lock (sync)
{
Stream tempbuf = swapbuf;
swapbuf = writebuf;
writebuf = tempbuf;
if (!firsttime)
{
Monitor.Pulse(sync);
}
else
{
firsttime = false;
}
}
//Thread.Sleep(1);
return writebuf;
}
}
}
使用第一次检查是因为第一次请求写入缓冲区时,它不能脉冲消费者,因为缓冲区仍然必须写入数据。当第二次询问 writebuffer 时,我们可以确定前一个缓冲区包含数据。
我有两个线程,一个生产者和一个消费者。 这是我的输出:
prod: uv_hjd`alv cons: N/<]g[)8fV
prod: N/<]g[)8fV cons: 5Ud*tJ-Qkv
prod: 5Ud*tJ-Qkv cons: 4Lx&Z7qqjA
prod: 4Lx&Z7qqjA cons: kjUuVyCa.B
prod: kjUuVyCa.B
现在消费者落后了也没关系,它应该这样做。 如您所见,我丢失了第一串数据,这是我的主要问题。
其他问题是这样的:
- 如果我删除第一次检查,它可以工作。但我认为不应该...
- 如果我添加一个 Thread.Sleep(1);在 GetWriteBuffer() 中它也可以工作。我不明白的东西。
提前感谢您的任何启发。
【问题讨论】: