C#信号量状态测试线程安全

时间:2014-04-16 00:10:35

标签: c# multithreading thread-safety

public class ThreadDemo
{

    Semaphore sem = new Semaphore(0, 1);//Semaphore with maxCount of 1

    public ThreadDemo()
    {
        Thread worker = new Thread(WorkerThread);
        worker.Start();
    }

    public void NotifyNewData()
    {
        //New data added to queue

        //WorkerThread could be in one of two states
        //1) still working or 
        //2) waiting for new data

        if (sem.WaitOne(0) == false)//If worker thread is waiting for new data
            sem.Release();//tell worker thread to process new data
    }

    private void WorkerThread()
    {
        while (true)
        {
            while(/*data in queue*/)
            {
                //process data in some queue
            }
            sem.WaitOne();//Worker thread processed all data, wait for more
        }
    }
}

参见上面的例子。

我有一个工作线程处理队列中的数据,我想让它在另一个线程通知时立即开始处理新数据。我不想轮询新数据。

以上解决方案是否有效?或者,即使存在可以处理的数据,此代码是否可能导致工作线程被阻塞?也许如果两个线程同时调用sem.WaitOne()。

0 个答案:

没有答案