我正在写一个音频应用程序,它有多个线程产生声音和一个线程混合声音并将它们发送到声卡。我已经尝试了几种线程同步方式,包括Signals和线程安全队列,但它们都太慢了。所以现在我为每个生产者使用一个bool来表明它的队列是否已满。它似乎工作得很好(32个线程的延迟为5ms),但这样做是否安全?使用bools来同步多个线程安全吗?
class PlayThreadParameters
{
public Queue<Samples> queue;
public bool isOutputQueueFull;
}
制片方是这样的:
public void PolyPlayThread(object o)
{
var playThreadParameters = (PlayThreadParameters)o;
while (isPlaying)
{
while (playThreadParameters.isOutputQueueFull)
{
if (!isPlaying)
return;
Thread.Sleep(1);
}
... //fill output queue
playThreadParameters.isOutputQueueFull = true;
}
}
消费者看起来像这样(由n音讯一个单独的线程调用):
public override int Read(byte[] array, int offset, int count)
{
for (int v = 0; v < playThreadParameters.Length; v++)
while (!playThreadParameters[v].isOutputQueueFull)
{
if (!isPlaying)
return 0;
Thread.Sleep(1);
}
... //mix the samples from the outputqueues
for (int v = 0; v < playThreadParameters.Length; v++)
playThreadParameters[v].isOutputQueueFull =false;
return count;
}
你是如何设置isPlaying变量的? – marcind 2010-11-15 01:03:51
@marcind当用户按下停止按钮时,isPlaying设置为false – 2010-11-15 01:14:43