Semaphore的應用

來源:互聯網
上載者:User
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace SynchronizationContext{    internal interface IQueueReader<T> : IDisposable    {        T Dequeue();        void ReleaseReader();    }    internal interface IQueueWriter<T> : IDisposable    {        void Enqueue(T data);    }    internal class BlockingQueue<T> : IQueueReader<T>, IQueueWriter<T>, IDisposable    {        // use a .NET queue to store the data        private Queue<T> mQueue = new Queue<T>();        // create a semaphore that contains the items in the queue as resources.        // initialize the semaphore to zero available resources (empty queue).        private Semaphore mSemaphore = new Semaphore(0, int.MaxValue);        // a event that gets triggered when the reader thread is exiting        private ManualResetEvent mKillThread = new ManualResetEvent(false);        // wait handles that are used to unblock a Dequeue operation.        // Either when there is an item in the queue        // or when the reader thread is exiting.        private WaitHandle[] mWaitHandles;        public BlockingQueue()        {            mWaitHandles = new WaitHandle[2] { mSemaphore, mKillThread };        }        public void Enqueue(T data)        {            lock (mQueue)            {                mQueue.Enqueue(data);                //mQueue.Enqueue(data);//test            }            // add an available resource to the semaphore,            // because we just put an item            // into the queue.            mSemaphore.Release();            //mSemaphore.Release(2);//test        }        public T Dequeue()        {            // wait until there is an item in the queue            WaitHandle.WaitAny(mWaitHandles);            lock (mQueue)            {                if (mQueue.Count > 0)                    return mQueue.Dequeue();            }            return default(T);        }        public void ReleaseReader()        {            mKillThread.Set();        }        void IDisposable.Dispose()        {            if (mSemaphore != null)            {                mSemaphore.Close();                mQueue.Clear();                mSemaphore = null;            }        }    }}

出處:http://www.codeproject.com/Articles/32113/Understanding-SynchronizationContext-Part-II

namespace SynchronizationContext{    class Program    {        static void Main(string[] args)        {            BlockingQueue<string> bq = new BlockingQueue<string>();            //線程t1向bq中延遲插入資料            Thread t1 = new Thread(() => { Thread.Sleep(4000); bq.Enqueue("test"); });            t1.Start();            //在t1將test加入到bq前,這個操作被阻塞4s左右            string d = bq.Dequeue();            Console.WriteLine("d:" + d);            //Semaphore使用保證了隊列中沒有東西的時候出出隊列的操作都是阻塞的            string d2 = bq.Dequeue();            Console.WriteLine("d2:" + d2);            string d3 = bq.Dequeue();            Console.WriteLine("d3:" + d3);        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.