簡體   English   中英

使用bool來同步多個線程是否安全?

[英]Is it safe to use bools to synchronize multiple threads?

我正在編寫一個音頻應用程序,它有多個線程產生聲音,一個線程混合聲音並將它們發送到聲卡。 我已經嘗試了幾種同步線程的方法,包括信號和線程安全隊列在內的“正確”方式,但它們都太慢了。 所以現在我為每個生產者使用bool來指示它的隊列是否已滿。 它似乎工作得很好(32個線程的5ms延遲),但這樣做是否安全?

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;
    }
}

消費者看起來像這樣(由Naudio的一個單獨的線程調用):

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;
        }

據我所知,.NET內存模型不保證在一個線程中生成的變量的更改將在另一個線程中可見。 你需要一個記憶障礙 組織的最簡單(盡管不是最有效)的方法是使用lockInterlocked方法。

順便說一句,忙碌的等待並不是實現目標的最佳方法。 也許您想切換到具有適當條件變量(C#parlance中的Monitor )使用的生產者 - 消費者模型

不,它不是完全安全的,但你可能在大多數時候都很幸運;-)你應該使用Interlocked方法來訪問bool。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM